Sunday, April 24, 2016

How to set up Edit for Remote Form in Rails? | Fixed issues

How to set up Edit for Remote Form in Rails? | Fixed issues


How to set up Edit for Remote Form in Rails?

Posted: 24 Apr 2016 07:05 AM PDT

Webpage View

So in the image button above, I have a button called "Mark Item as Done". Inside that Item table, I have a date: due_date, string: task_title, text: description, and a boolean: done.

Now I put the format.js in the todoitems_controller.rb because I figured that would be the best place to put it because I'm calling their edit link

edit_todolist_todoitem GET    /todolists/:todolist_id/todoitems/:id/edit(.:format) todoitems#edit  

Now, should I also be doing something to the def edit in the todoitems_controller.rb as well or just def update? And putting remote: true in the Todolists/_form.html.erb file, is it the best place to put it there or should I put it in Todoitems/_form.html.erb file? And after doing all these, what is the next step?

This is what I've managed to accomplish so far. I'm just struggling to get this started because the lectures are confusing. If there's anything else missing, I'm happy to provide more info about this! Any help would be appreciated!

TODOLIST.rb - Look at button_to. That's the part I need help

<body class="page">    <h1>      <%= @todolist.list_name %>    </h1>      <h2>      List due date: <%= @todolist.list_due_date %>    </h2>      <%= link_to 'Add Todo Item', new_todolist_todoitem_path(@todolist, @todoitem) %>      <p>      <% @paginate_items.each do |item| %>      <div class="list">          <% if item.due_date > Date.today %>          <% if item.done? %>            <a class="complete">              <%= item.due_date %>            </a>            <a class="linkResults">              <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %><br/> <br/>            </a>          <% else %>            <form class="oneLine">              <a class="notDue">                <%= item.due_date %>              </a>              <a class="linkResults">                <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %>                <%= button_to "Mark Item as Done", remote: true %><br/> <br/>              </a>            </form>          <% end %>        <% elsif item.due_date == Date.today %>          <% if item.done? %>            <a class="complete">              <%= item.due_date %>            </a>            <a class="linkResults">              <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %><br/> <br/>            </a>          <% else %>            <form class="oneLine">              <a class="dueToday">                <%= item.due_date %>              </a>              <a class="linkResults">                <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %>                <%= button_to "Mark Item as Done", remote: true %><br/> <br/>              </a>            </form>          <% end %>        <% else %>          <% if item.done? %>            <a class="complete">              <%= item.due_date %>            </a>            <a class="linkResults">              <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %><br/> <br/>            </a>          <% else %>            <form class="oneLine">              <a class="overdue">                <%= item.due_date %>              </a>              <a class="linkResults">                <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %>                <%= button_to "Mark Item as Done", remote: true  %><br/> <br/>              </a>            </form>          <% end %>        <% end %>      </div>      <% end %>    </p>      <br/>      <p><%= will_paginate @paginate_items %></p>      <%= link_to 'Delete Todo List', todolist_path, data: { confirm: "Delete this list?" }, method: :delete %> |    <%= link_to 'Edit Todo List', edit_todolist_path(@todolist) %> |    <%= link_to 'Back to Todo List', todolists_path %>  </body>  

todoitems_controller.rb - I already put the render.js in the update.

  def update      respond_to do |format|        if @todoitem.update(todoitem_params)          format.html { redirect_to @todolist, notice: 'Item was successfully updated.' }          format.json { render :show, status: :ok, location: @todoitem }          render.js        else          format.html { render :edit }          format.json { render json: @todoitem.errors, status: :unprocessable_entity }        end      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_todoitem        @todoitem = Todoitem.find(params[:id])      end        def set_todolist        @todolist = Todolist.find(params[:todolist_id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def todoitem_params        params.require(:todoitem).permit(:due_date, :task_title, :description, :done, :todolist_id)      end  

todolists/_form.html.erb - I already put the remote: true

<%= form_for(@todolist, remote: true) do |f| %>  

rspec controller spec for create action with factory

Posted: 24 Apr 2016 06:44 AM PDT

For some reason my controller specs for create action don't work. What did I miss?

factories

factory :profile do    first_name { "John" }    last_name { "Doe" }    job_title { Faker::Name.title }    company { "Faskyn" }    avatar { Faker::Avatar.image }    location { Faker::Address.city }    description { Faker::Lorem.sentence }    phone_number { Faker::PhoneNumber.cell_phone }    user  end    factory :product, class: Product do    name { Faker::Commerce.product_name }    company { Faker::Company.name }    website { 'https://example.com' }    oneliner { Faker::Lorem.sentence }    description { Faker::Lorem.paragraph }    user    trait :product_with_nested_attrs do      before(:create) do |product|        product.product_competitions << build(:product_competition, product: product)        product.product_usecases << build(:product_usecase, product: product)        product.product_features << build(:product_feature, product: product)        product.industries << build(:industry)      end    end  end   

posts_controller_spec

describe "POST create" do    before(:each) do      login_user    end    context "with valid attributes" do        it "saves the new profile in the db" do        expect{ post :create, user_id: @user.id, profile: attributes_for(:profile, user: @user) }.to change(Profile, :count).by(1)      end        before(:each) do        post :create, user_id: @user.id, profile: attributes_for(:profile, user: @user)      end        it { is_expected.to redirect_to add_socials_user_profile_path(@user) }    end  end  

error for profiles_controller_spec

ProfilesController POST create with valid attributes saves the new profile in the db   Failure/Error: expect{ post :create, user_id: @user.id, profile: attributes_for(:profile, user: @user) }.to change(Profile, :count).by(1)     expected #count to have changed by 1, but was changed by 0  

products_controller_spec

context "POST create" do    context "with valid attributes" do        it "saves the new product in the db" do        product_attrs = attributes_for(:product, :product_with_nested_attrs, user: @user)        expect{ post :create, product: product_attrs }.to change{ Product.count }.by(1)      end        it { is_expected.to redirect_to product_path(Product.last) }    end  end  

errors for products_controller_spec

ProductsController when user is logged in POST create with valid attributes saves the new product in the db   Failure/Error: expect{ post :create, product: product_attrs }.to change{ Product.count }.by(1)     expected result to have changed by 1, but was changed by 0    ProductsController when user is logged in POST create with valid attributes   Failure/Error: it { is_expected.to redirect_to product_path(Product.last) }     ActionController::UrlGenerationError:     No route matches {:action=>"show", :controller=>"products", :id=>nil} missing required keys: [:id]  

Live ios(swift) chat, with existing rails web application

Posted: 24 Apr 2016 06:51 AM PDT

I have an existing rails web application with a postgres DB running on the production server and I recently created an ios counter part. I am trying to implement a live chat message within the ios application (the web counter part does not have live chatting).

I have done some research and found that I need to create something called a TCPServer to have a constant communication between the ios application and my rails application. I used daemon to run a simple ruby script on my production server (beside my web application) to test the TCPServer and I was able to run a simple ruby client to connect to the ruby TCPServer and get some static messages.

I have no idea where to go from here. All examples of live ios chatting seem to be writing and receiving data to servers such as firebase. I do not want to do this because I already have a rails application communicating with a postgres database.

How can I get a live chat running on the ios counter part and have both the ios and the web rails communicating to the same database?

Rails: calculate stats and group by day

Posted: 24 Apr 2016 06:31 AM PDT

I am calculating statistics for my LaserSheet model to build a morris.js chart for a dashboard page. I currently have it working with one statistic:

# Show four Mondays ago up to this coming Sunday (4 weeks)  start_date = Time.zone.now.beginning_of_week - 3.weeks  end_date   = Time.zone.now.end_of_week    # Calculate sheets cut per day  empty_dates_hash = Hash[(start_date.to_date..end_date.to_date).collect { |v| [v, 0] }]    recent_cut_stats = LaserSheet.where('cut_at IS NOT NULL')                               .where('cut_at > ?', start_date.beginning_of_day)                               .where('cut_at < ?', end_date.end_of_day)                               .group("DATE(cut_at::TIMESTAMPTZ AT TIME ZONE '#{Time.zone.now.formatted_offset}'::INTERVAL)")                               .count  recent_cut_stats = empty_dates_hash.merge(recent_cut_stats)  

I would like to add a historical "sheets left to cut" stat grouped by day. To accomplish this, I need to find all LaserSheets for each day that were created_at on or before that date, where cut_at is either NULL or later than that date.

I can manually do this for yesterday:

LaserSheet.where('created_at < ?', Time.zone.yesterday.end_of_day)            .where('cut_at IS NULL OR cut_at > ?', Time.zone.yesterday.end_of_day)            .count  

and for today:

LaserSheet.where('created_at < ?', Time.zone.today.end_of_day)            .where('cut_at IS NULL OR cut_at > ?', Time.zone.today.end_of_day)            .count  

I could repeat this for each day in [start_date..end_date] but this is quite inefficient. Is there a way to accomplish this with one database query? It doesn't seem as trivial as simply grouping by day.

I am using PostgreSQL and Rails 4.

Validation fails with delegation error

Posted: 24 Apr 2016 06:04 AM PDT

I have the following model associations

class WarehouseVariant < AB    has_one :warehouse    has_one :variant    has_many :variant_cities  end    class VariantCity < AB    belongs_to :warehouse_variant    delegate :mrp_paise, :to => :warehouse_variant    validates :variant_id, uniqueness: { scope: :city_id }  end  

The spec is the following:

let!(:warehouse_variant) {create(:warehouse_variant) }  subject { create(:variant_city, max_discount_percent: 99.99, max_promotion_percent: 99.99, warehouse_variant: warehouse_variant) }    it { is_expected.to validate_uniqueness_of(:variant_id).scoped_to(:city_id)}  

The spec fails with the following error:

Module::DelegationError: VariantCity#mrp_paise delegated to warehouse_variant.mrp_paise, but warehouse_variant is nil: #

The thing is I inserted a debugging statement like this

it { binding.pry; is_expected.to validate_uniqueness_of(:variant_id).scoped_to(:city_id)}

and here the variant_city, has the object warehouse_variant, but when the test finishes I get the error mentioned above.

Any help would be appreciated.

Autoscale workers on Digital Ocean

Posted: 24 Apr 2016 06:58 AM PDT

I have 3 Webservers. DB, Web and Worker. The Worker is just processing sidekiq prcocess all day long.

As soon the Queue is over 100.000 jobs, i want to have a second worker instance and i do struggle a little bit with the right thinking of hot to do. (and if the queue is above 300.000 i need 3 workers, on and on).

  • I take my Workerand make a snapshot.
  • Via Digital-Ocean::API i wil create a new instance, based on that image.
  • As soon as the Instance is booting it needs to update the code from the Git-Repository
  • i need to tell the Database Server that he is allowed to receive connections from this instance IP

  • as soon the the queue is below 20.000 i can kill my instance.

Is this the right way of doing or are there better ways of how to do ? Am i missing something?

Additional Question:

on DB i only have mysql and redis. no ruby or anything else. so there is also no rails to run. If my worker decides, to create another worker, the new one needs to have access to mysql. it seems like to be impossible to create some access from a remote machine and it looks i need to create the access from the db server.

mysql> show grants;  +-----------------------------------------------------------------------------------------+  | Grants for rails@162.243.10.147                                                         |  +-----------------------------------------------------------------------------------------+  | GRANT ALL PRIVILEGES ON *.* TO 'rails'@'162.243.10.147' IDENTIFIED BY PASSWORD <secret> |  | GRANT ALL PRIVILEGES ON `followrado`.* TO 'rails'@'162.243.10.147'                      |  +-----------------------------------------------------------------------------------------+  2 rows in set (0.00 sec)    mysql> CREATE USER 'rails'@'162.243.243.127' IDENTIFIED BY 'swag';  ERROR 1227 (42000): Access denied; you need (at least one of) the CREATE USER privilege(s) for this operation  

Ruby on Rails 4 - FriendlyID ID's based on users?

Posted: 24 Apr 2016 06:56 AM PDT

Is it possible to separate IDs on a per user basis? For example;

I set up devise for users and friendly ID for nice slugs rather than 1, 2, 3 etc.

However, if two users make a todo with the same name, then it's still counted as a duplicate even if that user has never made a todo with that slug before?

I would like the slugs to be unique to each individual user as oppose to unique to the database.

I'm pretty sure this is all the friendly ID code in my application

class Todo < ActiveRecord::Base    belongs_to :user      extend FriendlyId    friendly_id :title, use: [:slugged, :history]  end  

Any help is greatly appreciated.

Javascript not executing after Rails redirect

Posted: 24 Apr 2016 05:55 AM PDT

My application contains a very simple login and two separate AJAX calls. I have a loading spinner that is hidden automatically whenever a page is ready it is contained in index.js

$(function() {       $("loading").hide();       $("#scan_button").on("ajax:success", function(e, data, status, xhr) {         $("#standard_results").hide();         $("#results").show();         $("#results").html(data);     });       $(document).ajaxStop(function() {         $("#loading").hide();     });       $(document).ajaxStart(function() {         $('#loading').show();     });    });  

When a user logs in the following happens

class SessionController < ApplicationController        def create          user = User.find_by(username: params[:session][:username])            if(user.password == params[:session][:password])              log_in user              redirect_to root_path          end      end        def destroy          logout          redirect_to root_path      end    end  

The route path takes me back to 'home#index' for which the index.js file exists. When the user logs in the redirect happens and the loading spinner is hidden and all JavaScript executes as expected.

When the user hits log out however the redirect occurs, but the loading spinner is shown and no JavaScript ever gets executed. Here is my index.html.erb file that contains the JavaScript.

<% content_for :title, "Network Monitor" %>      <div class="container-fluid">        <nav class="navbar narvbar-dark bg-inverse">          <span class="navbar-brand">Network Monitor</span>            <%= link_to "Scan", scan_path, remote: true, class: "btn btn-secondary", id: "scan_button" %>               <% if logged_in? %>                <span class="pull-xs-right"><%= link_to "Logout", logout_path, class: "btn btn-secondary" %></span>            <% else %>                <%= form_for(:session, url: login_path, :html => {:class => 'form-inline pull-xs-right'}) do |f| %>                    <%= f.text_field :username, class: 'form-control', placeholder: "Username" %>                  <%= f.password_field :password, class: 'form-control', placeholder: "Password" %>                  <%= f.submit "Log in", class: 'btn btn-primary', id: 'login_button' %>                <% end %>          <% end %>      </nav>        <div id="loading">          <%= image_tag "loading.gif", class: "loading_gif" %>        </div>        <div class="row">          <div class="col-md-12">              <div id="scan_bar">                  <h3>Welcome to your network monitor!</h3> <br />                    <p>To get started hit the scan button in the top right corner, this will detect the computers that are alive on your network and show them below.</p>              </div>          </div>      </div>        <div class="row">          <div id="results">      </div>      <div id="standard_results">      </div>  

Carrierwave Renaming Files

Posted: 24 Apr 2016 05:49 AM PDT

I have the following models

campaigns (id, name, ....)  campaign_creatives (id, file, campaign_id, ....)  

When i save the files in campagin_creatives i want the file name to be something like this

{campaign-name} + random-string.file-extension  

This is by present method to rename

def filename      if original_filename        "#{secure_token(8)}.#{file.extension}"      end    end      protected    def secure_token(length=16)      var = :"@#{mounted_as}_secure_token"      model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))    end  

How can i access the associated models name column for renaming the file?

relating has_and_belongs_to_many table to a fourth table

Posted: 24 Apr 2016 05:53 AM PDT

Thanks for the help first of all.

I have User(table) and has_and_belongs_to_many Products(table) with a joining table UserJoinProducts. I have this and works.

My problem is..

I want to create a table where Users have a records when they CheckIn or Out a Product and also have record of each Iteration.

I want user to have a record for each time they check_in or out the same product.

|user|produ| _date-- |in |

|bob | eggs |1/1/2016| X |

|bob | Coke |1/1/2016| X |

|bob | eggs |1/5/2016| -- |

|bob | Coke |1/7/2016| -- |

|bob | eggs |1/9/2016| X |

Click here for A sad example of my table ;) lol

Thanks Again For your Help.

Paperclip::Error in RegistrationsController#update There was an error processing the thumbnail

Posted: 24 Apr 2016 06:26 AM PDT

Paperclip::Error in RegistrationsController#update There was an error processing the thumbnail. Can some one help me on this !!! My registrations controller file is,

class RegistrationsController < Devise::RegistrationsController  protected      def update_resource(resource, params)          resource.update_without_password(params)      end  

end

My application controller file is

     class ApplicationController < ActionController::Base      protect_from_forgery with: :exception      before_action :configure_permitted_paramters, if: :devise_controller?      protected      def configure_permitted_paramters          devise_parameter_sanitizer.for(:sign_up) << :fullname           devise_parameter_sanitizer.for(:account_update) << :fullname <<  :current_password << :avatar      end  end  

Can someone help me to get rid of the error

My user model is,

has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"    validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/  

Rails get result from acts as taggable on by match degree?

Posted: 24 Apr 2016 04:40 AM PDT

I use gem acts-as-taggable-on, to add association between Articles and tags, I try three way in document:

Article.tagged_with(some.tag_list, :match_all => true)

return all matches articles from given tags

Article.tagged_with(some.tag_list, :wild => true)

return all matches articles from given tags(if articles have more tags than given, but include all given tags, will be return too.)

Article.tagged_with(some.tag_list, :any => true)

return any matches articles from given tags

but three methods not match what I want, I want something like this: 1.given 3 tags(A,B,C) 2.return articles order by match degree, first part is match all(A,B,C), then (A,B), then (A,C), then (B,C), then (A),...and so on.

in document, seems that I can only use match_all method and merge the result, does any better way to accomplish this?

Limit Elasticsearch results to one particular sub-class or all of them

Posted: 24 Apr 2016 04:45 AM PDT

I have followed this guy's tutorial to setup Elasticsearch on Rails with Mongoid.

My modelisation goes like this

class Generic    include Mongoid::Document    include Searchable    index_name "generic-#{Rails.env}"  end    class Foo < Generic    index_name "generic-#{Rails.env}"    document_type "foo"  end    class Bar < Generic    index_name "generic-#{Rails.env}"    document_type "bar"  end  

I am importing the Foo and Bar models in the index of my Generic model. The advantage is then that I can use all the features from Generic.search(q).records, since it is a Mongoid::Criteria and my codebase currently only works with instanciated models.

How can I limit the results to either Foo or Bar classes or both ? I need something like

if @query.wants_only_foo?    Professional.search(@q).only_foo   else    Professional.search(@q)  end  

Note : a second approach would have been to maintain separate indexes on both Foo and Bar, and use Elasticsearch::Model.search(@query, [Foo, Bar]) but then it becomes much harder to use the search results (I would have to rewrite some code to work with response.results, rather than response.records). I know this ideally the best way to go, but right now it would mean extra work so I need a faster solution.

Initial Capistrano - Puma - Rails setup and issues

Posted: 24 Apr 2016 04:15 AM PDT

I am working on an OSX host and an openBSD guest with Vagrant. So far everything is good and I have a Rails application that I would like to deploy to the guest system.

Initially some scripts run and provision the system. Then I cap staging deploy and the application is being deployed successfully to it. I have choosen puma as a webserver.

These are my Capistrano files:

Capfile

require 'capistrano/setup'  require 'capistrano/deploy'  require 'capistrano/rails'  require 'capistrano/bundler'    Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }  Dir.glob('lib/capistrano/**/*.rb').each { |r| import r }  

deploy.rb

# config valid only for current version of Capistrano  lock '3.4.1'    set :application, 'my_app'  set :repo_url, 'git@git.....'    # Default branch is :master  set :branch, "AA-103"    # Default deploy_to directory is /var/www/my_app_name  set :deploy_to, '/home/its_me/my_app'    # Default value for :scm is :git  set :scm, :git    # Setup user for deploys  set :user, "vagrant"  set :use_sudo, true    # Setup rails environment  set :rails_env, "staging"    # Default value for :format is :pretty  # set :format, :pretty    # Default value for :log_level is :debug  # set :log_level, :debug    # Default value for :pty is false  # set :pty, true    # which config files should be copied by deploy:setup_config  # see documentation in lib/capistrano/tasks/setup_config.cap  # for details of operations  set(:config_files, %w(    database.example.yml    secrets.example.yml  ))    # files we want symlinking to specific entries in shared.  set :linked_files, %w{config/database.yml}    # dirs we want symlinking to shared  set :linked_dirs, %w{    bin    log    tmp/pids    tmp/cache    tmp/sockets    vendor/bundle    public/system  }    # Default value for default_env is {}  # set :default_env, { path: "/opt/ruby/bin:$PATH" }    # Default value for keep_releases is 5  set :keep_releases, 3    namespace :deploy do      desc "Override deploy:cold to NOT run migrations - there's no database"      task :cold do          update          start      end      desc 'Upload YAML files.'      task :upload_yml do        on roles(:app) do          #execute "mkdir #{shared_path}/config -p"          upload! StringIO.new(File.read("config/database.yml")), "#{shared_path}/config/database.yml"          upload! StringIO.new(File.read("config/secrets.yml")), "#{shared_path}/config/secrets.yml"        end      end    end  

The first issue is about Web Servers. I tried running puma inside the "current" folder and i am getting an error like this:

/usr/local/lib/ruby/gems/2.3/gems/puma-3.4.0/lib/puma/runner.rb:103:in `reopen': No such file or directory - /home/deploy/my_app/releases/20160424103750/shared/log/puma.stdout.log (Errno::ENOENT)  

If I try to run rails server inside the same folder, I get the rails help page (rails -h).

What is happening? The file that puma complains about, exists. It seems I must have done something very wrong. Where do I go from here ?

rspec matcher for build in new action

Posted: 24 Apr 2016 04:12 AM PDT

How/with which matcher can I test if @product.industry_products.build and the rest are defined in my action?

products_controller

def new    @product = Product.new    authorize @product    @product.industry_products.build    @product.product_features.build    @product.product_usecases.build    @product.product_competitions.build  end      

products_controller_spec.rb

context "GET new" do    let!(:profile) { create(:profile, user: @user) }    before(:each) do      get :new    end      it "assigns product" do      expect(assigns(:product)).to be_a_new(Product)    end      it { is_expected.to respond_with 200 }    it { is_expected.to render_template :new }  end  

Strange behaviour about rendered file's size

Posted: 24 Apr 2016 05:59 AM PDT

In controller, I have something like this:

respond_to do |format|    format.ini do      response.headers['Content-Disposition'] = "attachment; filename=somefile.ini"      render ini: SomeClass.make_ini(data)    end  end  

SomeClass.make_ini(data) renders the correct ini file (1.5MB) for API users. There is a task from our clients to add Content-Length header. The reason doesn't matter.

When I try:

respond_to do |format|    format.ini do      file = SomeClass.make_ini(data)      response.headers['Content-Length'] = file.size.to_s      response.headers['Content-Disposition'] = "attachment; filename=somefile.ini"      render ini: file    end  end  

file.size.to_s brings 1301761. And after setting Content-Length, the rendered file is 1.2MB. And content is cut.

I would be grateful if someone could tell the reason.

CSS dropdown menu using W3schools example

Posted: 24 Apr 2016 03:32 AM PDT

I'm attempting to create a dropdown menu using W3schools example method, but I can't seem to get the menu to stay open when moving the cursor away from the button. At first I thought my code was wrong, so I directly copied the W3schools code to my files, but still got the same result.

CSS code:

.personal-dropbtn {      border: none;      cursor: pointer;  }    .personal-dropdown {      position: relative;      display: inline-block;  }    .personal-dropdown-content {      background: #DDD;      display: none;      position: absolute;      right: 0;  }    .personal-dropdown-content a {      display: block;  }    .personal-dropdown-content a:hover {  }    .personal-dropdown:hover .personal-dropdown-content {      display: block;  }  

HTML code:

<% if user_signed_in? %>      <div class="personal-dropdown">          <button class="personal-dropbtn"><%= current_user.username %></button>          <div class="personal-dropdown-content">              <%= link_to 'Profil', user_path(current_user) %>              <%= link_to 'Logg ut', destroy_user_session_path %>              <%= link_to 'Lag quiz', new_quiz_path %>          </div>      </div>  

As you can see, I'm utilizing Ruby on Rails to create the website. I'm wondering if that might be breaking the menu in some way? I plugged my code without the Ruby incjection into JSfiddle and it worked there, so I can only conclude that Rails might be disturbing somehow?

Rails - Conflicts between jQuery and javascript

Posted: 24 Apr 2016 03:14 AM PDT

I'm having a problem loading gems into my Rails 4 app.

I use jQuery. In my application.js, I have:

//= require jquery  //= require bootstrap-sprockets  //= require jquery_ujs  //= require html.sortable  //= require disqus_rails  //= require moment  //= require bootstrap-datetimepicker  //= require pickers  //= require main  //= require hammer.min  //= require jquery.animate-enhanced.min  //= require jquery.countTo  //= require jquery.easing.1.3  //= require jquery.fitvids  //= require jquery.magnific-popup.min  //= require jquery.parallax-1.1.3  //= require jquery.properload  //= require jquery.shuffle.modernizr.min  //= require jquery.sudoSlider.min  //= require jquery.superslides.min  //= require masonry.pkgd.min  //= require rotaterator  //= require smoothscrolljs  //= require waypoints.min  //= require wow.min  //= require gmaps/google  //= require chosen-jquery  //= require cocoon  //= require imagesloaded.pkgd.min  //= require isotope.pkgd.min  //= require jquery.counterup.min  //= require jquery.pjax  //= require custom.js  //= require slider  //= require dependent-fields  //= require bootstrap-slider    $.noConflict();  jQuery( document ).ready(function( $ ) {    // Code that uses jQuery's $ can follow here.      $(document).ready(function() {          DependentFields.bind()      });  });      //= require_tree .  

In my gem file, I am trying to use rails dependent fields gem. That gem also requires underscore.js.

I think the reason this gem isn't working is because it uses javascript.

I'm having the same problem with the disqus rails gem (which is raising errors that are localhost/:94 Uncaught TypeError: $ is not a function

Does anyone know how to resolve conflicts between rails jQuery and javascript?

How to get current_user.id after signup in devise [on hold]

Posted: 24 Apr 2016 02:12 AM PDT

I want to get id of user which successfully signup in devise registration.How can I do that?

Is it possible?

calling a rails controller method with javascript

Posted: 24 Apr 2016 02:14 AM PDT

I got a javascript funktion:

function handlePercentage(filledInPixels) {    filledInPixels = filledInPixels || 0;    console.log(filledInPixels + '%');    if (filledInPixels > 80) {      canvas.parentNode.removeChild(canvas);    }  }  

Now I want to access a rails controller to check a random string when filledInPixels > 80

How can I do that without reloading the page?

How can I fix ActionController::ParameterMissing in ReservationsController#create? [duplicate]

Posted: 24 Apr 2016 01:55 AM PDT

This question already has an answer here:

I've been trying to fix the following error for almost 8 hours:

Param is missing or the value is empty: reservations    Application Trace | Framework Trace | Full Trace    app/controllers/reservations_controller.rb:18:in `reservations_params'  app/controllers/reservations_controller.rb:11:in `create'  

Can someone please help me fix it? My code is below.

new.html.rb source:

<%= form_for @reservations do |f| %>      <%= f.label :table_number %><p &nbsp;>      <select name="table_number">        <option>1</option>        <option>2</option>        <option>3</option>        <option>4</option>        <option>5</option>        <option>6</option>        <option>7</option>        <option>8</option>        <option>9</option>        <option>10</option>        <option>11</option>        <option>12</option>      </select><br><br>      <label>Number of Seats:</label><p &nbsp;>      <%= f.text_field :num_seats %><br><br>      <label>Number of Guest:</label><p &nbsp;></p>      <%= f.text_field :guest_size  %><br><br>      <label>Reservation Time </label><p &nbsp;>      <%= f.time_select :requested_time %><br><br> <!-- ,{ampm: true} -->      <%= f.submit class: "rc_btn_02" %><br><br>  <% end %>  

reservations_controller.rb source:

def index       @reservations = Reservation.new  end    def new      @reservations = Reservation.new  end  def create      @reservations = Reservation.new(reservations_params)      @reservations.save      redirect_to @reservations  end      def reservations_params          params.require(:reservations).permit( :table_number,:num_seats,:guest_size,:requested_date,:requested_time)  end  

Error Message:

This is the error message.

rspec controller testing: "expected #count to have changed by -1, but was changed by 0"

Posted: 24 Apr 2016 02:43 AM PDT

am having trouble resolving this error. I'm not sure which part of the controller_spec is written wrongly. Please help!

Routes

Rails.application.routes.draw do    resources :cases, only: [:index, :show, :new, :create, :edit, :update] do      resources :links, only: [:create, :destroy]    end  end  

Controller

class LinksController < ApplicationController      before_action :prepare_case      def destroy      @link = @case_file.links.find(params[:id])      @link.destroy      redirect_to case_path(@case_file)    end      private      def prepare_case      @case_file = CaseFile.find(params[:case_id])    end  end  

spec/factories

FactoryGirl.define do      factory :link do        case_file      url 'www.google.com'        trait :invalid do        case_file nil        url ''      end    end  end  

spec/controllers

require 'rails_helper'    RSpec.describe LinksController, type: :controller do      let(:user) { build(:user) }    before { login_user user }    #for user log in      let(:case_file) { create(:case_file) }    let(:link) { create(:link, case_file: case_file) }      describe "DELETE destroy" do      it "deletes a link" do        expect { delete :destroy, id: link.id , case_id: case_file }.        to change(Link, :count).by(-1)         expect(response).to redirect_to(case_path(case_file))      end    end  end  

Error Message

$ rspec spec/controllers/links_controller_spec.rb ...F

Failures:

1) LinksController DELETE destroy deletes a link Failure/Error: expect { delete :destroy, id: link.id , case_id: case_file }. to change(Link, :count).by(-1)

expected #count to have changed by -1, but was changed by 0 # ./spec/controllers/links_controller_spec.rb:28:in `block (3 levels) in '

Finished in 1.18 seconds (files took 5.03 seconds to load) 4 examples, 1 failure

Failed examples:

rspec ./spec/controllers/links_controller_spec.rb:27 # LinksController DELETE destroy deletes a link

Pundit Policy issue, correct wikis not show

Posted: 24 Apr 2016 01:25 AM PDT

I want different types of wikis to appear on the index view depending on the role of the user. The policy for admin and standard / guest users work as it should but when it comes to premium users and collaborations it gets a little messy.In my app i have the ability to add Collaborators to private Wikis . So when im logged in as a premium user i get my private wikis and non private wikis but not any wikis where i am a collaborator of. Could it have to do with my Policy or my model associations .

wiki#index

  def index      @wikis = Kaminari.paginate_array(policy_scope(Wiki)).page(params[:page]).per(10)    end  

user model

class User < ActiveRecord::Base    has_many :wikis    has_many :collaborators    belongs_to :collaborators  ....  

Wiki model

    class Wiki < ActiveRecord::Base        belongs_to :user        has_many :collaborators        has_many :users, through: :collaborators  ....  

collaborator model

class Collaborator < ActiveRecord::Base    belongs_to :user    belongs_to :wiki  end  

Wiki_policy

   class Scope       attr_reader :user, :scope         def initialize(user, scope)         @user = user         @scope = scope       end         def resolve         wikis = []         if user.role == 'admin'           wikis = scope.all # if the user is an admin, show them all the wikis         elsif user.role == 'premium'           all_wikis = scope.all           all_wikis.each do |wiki|             if wiki.private == false || wiki.owner == user || wiki.collaborators.include?(user)               wikis << wiki # if the user is premium, only show them public wikis, or that private wikis they created, or private wikis they are a collaborator on             end           end         else # this is the lowly standard user           all_wikis = scope.all           wikis = []           all_wikis.each do |wiki|             if wiki.private == false || wiki.collaborators.include?(user)               wikis << wiki # only show standard users public wikis and private wikis they are a collaborator on             end           end         end         wikis # return the wikis array we've built up       end     end  

How to plan a model relation for collage admission app in rails

Posted: 24 Apr 2016 05:02 AM PDT

I want a basic student Registration & Login facility.

After login, the student should be directed to a Registration Form which contains forms for student contact details and student marks.

Student contact details form contains

student contact form      first name      last name      address      mobile no      gender      fathers name      fathers occupation      mothers name.    

Student marks list contains

**registration form**      .      |-- Board of examination      |   `-- Branches(ex:science,:humanities)      |       `--science[when i choose science]                 `--science subject1                 `--science subject2                 `--common paper for sciecnce and humanities      |       `--humanities[when is choose humanities]                 `--humanities subject1                 `--humanities subject2                 `--common paper for sciecnce and humanities  

How to set route with a slash

Posted: 24 Apr 2016 12:54 AM PDT

This is what i have for my routes right now:

route

What would be the format to add that to the routes like localhost:3000/appointments/new?

Nested Resources in Rails 4

Posted: 24 Apr 2016 12:36 AM PDT

Im attempting to create a Rails app that manages temperatures for a garden. I have setup my controllers and models appropriately to have resources for Grow - Tray - Plant. Grow has many trays Tray has many Plants

Im able to create nested trays in each grow. But I am not able to create plants in a designated tray.

The github repo

Im getting the following error: undefined method `tray' This is for my plant _form

<%= form_for([@grow, @grow.tray.plants.build]) do |f| %>  <div class="field">      <%= f.label :title %><br>      <%= f.text_field :title %>    </div>    <div class="field">      <%= f.label :description %><br>      <%= f.text_area :description %>    </div>    <div class="field">      <%= f.label :tray_id %><br>      <%= f.text_field :tray_id %>    </div>    <div class="actions">      <%= f.submit %>    </div>  <% end %>  

The routes look as such:

resources :grows do      resources :trays do        resources :plants      end  end  

The form for building the tray looks like this and it works:

<%= form_for([@grow, @grow.trays.build]) do |f| %>      <div class="field">      <%= f.label :title %><br>      <%= f.text_field :title %>    </div>    <div class="field">      <%= f.label :description %><br>      <%= f.text_area :description %>    </div>    <div class="field">      <%= f.label :grow_id %><br>      <%= f.text_field :grow_id %>    </div>    <div class="actions">      <%= f.submit %>    </div>  <% end %>  

Is this even the right approach?

"Data has contents that are not what they are reported to be" - Paperclip with CKEditor

Posted: 23 Apr 2016 11:28 PM PDT

I am getting a following error when uploading an image with CKEditor + Paperclip on Rails. "Data has contents that are not what they are reported to be". What I have done so far:

  1. Installed ImageMagick and set the PATH and development.rb with Paperclip.options[:command_path] = 'C:\Program Files (x86)\ImageMagick-6.9.3-Q16'
  2. Tried removing all the validations and styles in model file
  3. Installed thefile.exe and set the PATH
  4. Tried changing Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'in development.rb file which will give me Paperclip::NotIdentifiedByImageMagick error

Update

Changing a validations in model requires an server restart, apparently. I changed validates_attachment_content_type in ckeditor\picture.rb to validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"] which eliminates the error but gives me this: transformed to long black image

Shoppe category routing

Posted: 23 Apr 2016 11:02 PM PDT

I'm stuck with a little problem with displaying Shoppe categories. I want the category name and image displayed on my index page, category name acts as a link to the category page, where products of this category are displayed. I have the following code in my view:

<% @products.each do |category, products| %>      <%=  link_to category.name, product_category_path %>  <% end %>  

but it returns me an error undefined local variable or method 'product_category_path' for #<#<Class:0xb22076fc>:0xb2205870>

should I make a controller for categories, as well as for products? Because now I have only products_controller.rb with the following code:

class ProductsController < ApplicationController      def index          @products = Shoppe::Product.root.ordered.includes(:product_categories, :variants)          @products = @products.group_by(&:product_category)      end      def show          @product = Shoppe::Product.root.find_by_permalink(params[:permalink])      end  end  

Running ruby third party code [on hold]

Posted: 23 Apr 2016 10:23 PM PDT

I made a rails app with relationships between models. I need to generate a class diagram using this external code found in this article. I do not know how to run it. I tried typing ruby yumler.rb, but I can't get the diagrams.

Rails Wicegrid checkbox filter

Posted: 23 Apr 2016 10:39 PM PDT

I'm using wice grid in my application. I have a model which is having a highlight attribute with boolean values. In wice grid table, I do not want to use the default dropdown filter, instead use some checkbox or toggle button.

<%= grid(event_grid) do |g|    g.column name: 'Highlight', attribute: 'highlight' do |event|      event.highlight    end  end -%>  

By default, the filter is dropdown with true and false values. I want to have a checkbox filter instead of dropdown. Let me know if you need any more details... Thanks

No comments:

Post a Comment