Wednesday, November 30, 2016

How to reuse HTTP connection and share it between Sidekiq background jobs? | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

How to reuse HTTP connection and share it between Sidekiq background jobs? | Fixed issues


How to reuse HTTP connection and share it between Sidekiq background jobs?

Posted: 30 Nov 2016 08:18 AM PST

My app sends multiple API requests and get responses in background jobs to third party server. For now every job opens new Http connection and closes it after receiving a response. If it's possible to share this connection between all my app's jobs? How to keep it alive while a pool of jobs is in progress? How to close it at the end? Thanks.

How to destroy delayed jobs of particular queue?

Posted: 30 Nov 2016 08:14 AM PST

There is a Resque+Redis(and RoR of course) and a queue containing delayed jobs that I want to delete. I found is how to destroy certain queue that is active How to destroy jobs enqueued by resque workers? but it doesn't destroy delayed jobs of that queue

Missing required keys after submitting form

Posted: 30 Nov 2016 08:09 AM PST

I have the form for creating new school in city which doesn't work on creating; it returns me an error with undefined parameter :id for city_path.

<% if controller.action_name == "edit" %>        <% if @school.errors.any? %>          <div class="errors alert alert-danger">              <ul>                  <% @school.errors.full_messages.each do |msg| %>                      <li><%= msg %></li>                  <% end %>              </ul>          </div>      <% end %>        <%= form_for @school, url: school_path(@school) do |f| %>            <%= f.label "Ime:" %>          <%= f.text_field :name, class: "form-control input-field" %>            <%= f.label "URL slike:" %>          <%= f.text_field :icon_url, class: "form-control input-field" %>            <%= link_to school_path(@school), class: "btn btn-default", "data-no-turbolink": true do %>              <i class="fa fa-chevron-left"></i> &nbsp; Nazad          <% end %>            <%= button_tag(type: "submit", class: "btn btn-default") do %>              <i class="fa fa-check"></i> &nbsp; Pošalji          <% end %>        <% end %>    <% else %>        <% if @school.errors.any? %>          <div class="errors">              <ul>                  <% @school.errors.full_messages.each do |msg| %>                      <li><%= msg %></li>                  <% end %>              </ul>          </div>      <% end %>        <%= form_for @school, url: city_schools_path do |f| %>            <%= f.label "Ime:" %>          <%= f.text_field :name, class: "form-control input-field" %>            <%= f.label "URL slike:" %>          <%= f.text_field :icon_url, class: "form-control input-field" %>            <%= link_to city_path(@city), class: "btn btn-default", "data-no-turbolink": true do %>              <i class="fa fa-chevron-left"></i> &nbsp; Nazad          <% end %>            <%= button_tag(type: "submit", class: "btn btn-default") do %>              <i class="fa fa-check"></i> &nbsp; Pošalji          <% end %>        <% end %>    <% end %>  

When I try to send the form I get this error:

No route matches {:action=>"show", :controller=>"cities", :id=>nil} missing required keys: [:id]

This is my city_controller:

class CitiesController < ApplicationController        def index          @cities = City.all      end        def show          find_city          @schools = @city.schools.all      end        def new          @city = City.new      end        def edit          find_city      end        def update          find_city            if @city.update(city_params)              redirect_to city_path(@city)          else              render "edit"          end      end        def create          @city = City.new(city_params)            if @city.save              redirect_to index_path          else              render "new"          end      end        private        def find_city          @city = City.find(params[:id])      end        def find_schools          @schools = @city.schools.all      end        def city_params          params.require(:city).permit(:name, :icon_url)      end    end  

And this is school_controller:

class SchoolsController < ApplicationController        def index          find_city          @schools = @city.schools.all       end        def new          find_city          @school = @city.schools.new      end        def create          find_city            @school = @city.schools.new(school_params)            if @school.save              redirect_to school_path(@city, @school)          else              render "new"          end      end        def show          find_school            @search = @school.users.ransack(params[:q])          @city = @school.city            if (params.has_key?(:q))              @users = @search.result          else              # Prikazivanje svih korisnika koji su iste generacije kao i              # poslednji dodati korisnik              #@users = @school.users.where(generation: User.last.generation).order("sclass ASC")              #@sclasses = @school.sclasses.where(generation: Sclass.last.generation).order("name ASC")              if Sclass.last.nil?                  @sclasses = @school.sclasses.all              else                  @sclasses = @school.sclasses.where(generation: Sclass.last.generation).order("name ASC")              end          end      end        def edit          find_school      end        def update          find_school            if @school.update(school_params)              redirect_to school_path(@school)          else              render "edit"          end      end        def destroy          find_city          find_school            @school.destroy          redirect_to city_path(@city)       end        private        def find_city          @city = City.find(params[:city_id])      end        def find_school          @school = School.find(params[:id])      end        def school_params          params.require(:school).permit(:name, :icon_url)      end    end  

Here is the school show view:

<% title "#{@school.name}" %>    <div class="row">      <div class="col-md-12 text-center city-title">          <h3><%= @school.name %></h3>      </div>  </div>    <%= search_form_for @search, url: school_path(@school) do |f| %>      <div class="row input-field">          <div class="text-center">              <%= f.text_field :full_name_cont, placeholder: "Pretraga učenika" %>          </div>      </div>      <div class="row input-field">          <div class="text-center">              <%= f.select :generation_eq, options_from_collection_for_select(@school.users.order("generation DESC").select(:generation).uniq, "generation", "generation", @search.generation_eq), {}, { :class => "selectpicker" } %>          </div>      </div>      <div class="row input-field">          <div class="text-center">              <%= f.submit "Traži", class: "btn btn-default" %>          </div>      </div>  <% end %>    <div class="container">      <div class="row">          <div class="col-md-12">                <%= link_to city_path(@school.city), class: "btn btn-default" do %>                  <i class="fa fa-chevron-left"></i> &nbsp; Nazad-->              <% end %>                <% if is_admin? %>                  <%= link_to edit_school_path(@school), class: "btn btn-default" do %>                      <i class="fa fa-pencil"></i> &nbsp; Uredi školu                  <% end %>                    <%= link_to new_school_sclass_path(@school), class: "btn btn-default" do %>                      <i class="fa fa-plus"></i> &nbsp; Dodaj razred                  <% end %>                    <%= link_to new_school_generation_picture_path(@school), class: "btn btn-default" do %>                      <i class="fa fa-plus"></i> &nbsp; Dodaj tablo                  <% end %>              <% end %>          </div>      </div>  </div>    <div class="container">      <div class="users">          <% if !@users.nil? %>                <% @users.in_groups_of(4, false).each do |users| %>                    <div class="row">                        <% users.each do |user| %>                          <div class="col-xs-6 col-md-3 text-center">                              <a href="<%= user_path(@city, @school, user.sclass, user) %>" class="thumbnail school" data-no-turbolink="true">                                      <%= image_tag user.avatar.url(:thumb), size: "100", class: "user-profile-image img-responsive" %>                                      <%= user.full_name %> <br/>                                       <span class="badge">                                          <%= show_user_class(user.sclass.name) %>                                      </span>                              </a>                          </div>                      <% end %>                    </div>                <% end %>            <% else %>                <% @sclasses.in_groups_of(4, false).each do |sclasses| %>                    <div class="row">                        <% sclasses.each do |sclass| %>                          <div class="col-xs-6 col-md-3 text-center">                              <a href="<%= sclass_path(sclass) %>" class="thumbnail school" data-no-turbolink="true">                                  <%= image_tag sclass.icon_url, class: "img-responsive" %>                                  <%= show_user_class(sclass.name) %>                              </a>                          </div>                      <% end %>                    </div>                <% end %>              <% end %>        </div>  </div>  

Routes:

                       Prefix Verb   URI Pattern                                    Controller#Action                           root GET    /                                              welcome#index                          index GET    /pocetna(.:format)                             welcome#index                       new_cart GET    /korpa(.:format)                               carts#new                        success GET    /poslato(.:format)                             carts#success                       sessions POST   /sessions(.:format)                            sessions#create                    new_session GET    /sessions/new(.:format)                        sessions#new                        session DELETE /sessions/:id(.:format)                        sessions#destroy                          login GET    /prijava(.:format)                             sessions#new                        prijava POST   /prijava(.:format)                             sessions#create                         logout GET    /odjava(.:format)                              sessions#destroy                         odjava DELETE /odjava(.:format)                              sessions#destroy                school_sclasses GET    /skola/:school_id/razred(.:format)             sclasses#index                                POST   /skola/:school_id/razred(.:format)             sclasses#create              new_school_sclass GET      /skola/:school_id/razred/dodaj(.:format)     sclasses#new                    edit_sclass GET    /razred/:id/uredi(.:format)                    sclasses#edit                         sclass GET    /razred/:id(.:format)                          sclasses#show                                PATCH  /razred/:id(.:format)                          sclasses#update                                PUT    /razred/:id(.:format)                          sclasses#update                   school_users GET    /skola/:school_id/ucenik(.:format)             users#index                                POST   /skola/:school_id/ucenik(.:format)             users#create                new_school_user GET      /skola/:school_id/ucenik/dodaj(.:format)     users#new                      edit_user GET    /ucenik/:id/uredi(.:format)                    users#edit                           user GET    /ucenik/:id(.:format)                          users#show                                PATCH  /ucenik/:id(.:format)                          users#update                                PUT    /ucenik/:id(.:format)                          users#update                                DELETE /ucenik/:id(.:format)                          users#destroy     school_generation_pictures POST   /skola/:school_id/tablo(.:format)              generation_pictures#create  new_school_generation_picture GET    /skola/:school_id/tablo/novi(.:format)         generation_pictures#new        edit_generation_picture GET    /tablo/:id/uredi(.:format)                     generation_pictures#edit             generation_picture GET    /tablo/:id(.:format)                           generation_pictures#show                                PATCH  /tablo/:id(.:format)                           generation_pictures#update                                PUT    /tablo/:id(.:format)                           generation_pictures#update                   city_schools POST   /gradovi/:city_id/skola(.:format)              schools#create                new_city_school GET      /gradovi/:city_id/skola/nova-skola(.:format) schools#new                    edit_school GET    /skola/:id/uredi(.:format)                     schools#edit                         school GET    /skola/:id(.:format)                           schools#show                                PATCH  /skola/:id(.:format)                           schools#update                                PUT    /skola/:id(.:format)                           schools#update                         cities POST   /gradovi(.:format)                             cities#create                       new_city GET    /gradovi/novi(.:format)                        cities#new                      edit_city GET    /gradovi/:id/uredi(.:format)                   cities#edit                           city GET    /gradovi/:id(.:format)                         cities#show                                PATCH  /gradovi/:id(.:format)                         cities#update                                PUT    /gradovi/:id(.:format)                         cities#update                          carts GET    /carts(.:format)                               carts#index                                POST   /carts(.:format)                               carts#create                      edit_cart GET    /carts/:id/edit(.:format)                      carts#edit                           cart GET    /carts/:id(.:format)                           carts#show                                PATCH  /carts/:id(.:format)                           carts#update                                PUT    /carts/:id(.:format)                           carts#update                                DELETE /carts/:id(.:format)  

Also, form is submitting :id and :format parameters forming weird URL (http://localhost:3000/skola/1.17).

How do I install an existing rails app alongside a WAMP server?

Posted: 30 Nov 2016 08:07 AM PST

I am working on making a website and need to install rails alongside WAMP everything I have found is to install a new rails app i need to install an existing rails application alongside a WAMP server. Anyone know how to do that?

active record query order where first

Posted: 30 Nov 2016 08:22 AM PST

I am using c9 cloud ruby on rails and rails version is 5.0.0.1

I want to use active record query to select best rating restaurant and not have been visited yesterday. When I applied all where, order and first syntax in the query, it pops up error and but if I don't put where or don't use order, it works fine:

This works:

restaurant1= Restaurant.order('rating').last!  @suggested_restaurants=restaurant1.name  

This gives strange results:

restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}  @suggested_restaurants=restaurant1  

results: #<ActiveRecord::QueryMethods::WhereChain:0x000000046af7f8>

This triggered error:

restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}.last  @suggested_restaurants=restaurant1  

error: undefined methodlast' for #ActiveRecord::QueryMethods::WhereChain:0x00000004587a10>`

I can get around this issue by find_by_sql but really wants to know why and how to use "where" in rails 5. Thanks a lot!!

simple_form devise ActionView::Template::Error (wrong number of arguments (1, 0))

Posted: 30 Nov 2016 07:49 AM PST

I have upgraded rails to 5.0.0.1 and ruby 2.3.0 now I'm getting following error in my devise view using simple_form

ActionView::Template::Error (wrong number of arguments (given 1, expected 0)):

at this line of code

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-horizontal' }) do |f| %>  

I have googled this for hours and cannot find any solution,

my devise version is 4.2.0 and simple_form 3.3.1

Custom headers missing on production Rails site

Posted: 30 Nov 2016 07:48 AM PST

I've built an API that uses token-based auth and it's working fine on my local dev environment, using Puma. However, I've just deployed it onto a Nginx/Puma stack and noticed that custom headers are going missing.

When my header is called Authorization, it's not available within the app. However, if I call it X-Authorization then it works as expected.

Of course, I can just use the X- format but I'm curious as to why it's being filtered out and to whether it's Nginx, Puma or something else entirely that is doing it.

My Nginx config contains the following:

  location @app {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host;      proxy_redirect off;      proxy_pass http://{{ app_name }};    }  

I'm also using the rack-cors gem, set up as follows:

config.middleware.insert_before 0, Rack::Cors do    allow do      origins '*'      resource '*',      :headers => :any,      :methods => [:get, :post, :delete, :put, :patch, :options, :head]    end  end  

Query a JSONB column from a has_many :through relations

Posted: 30 Nov 2016 07:30 AM PST

Hi I am trying to do a query on a JSONB column from a has_many :through association.

class App    has_many: events, through: :event_types  end    class EventType    has_many :events, dependent: :destroy  end    class Event    belongs_to :event_type  end  

Event model has a jsonb column name 'properties'

app.events   

will return

Event::ActiveRecord_Associations_CollectionProxy  

not

ActiveRecord Relations  

I have an Event as such:

 #<Event:0x007fc91a8bc0c8    id: 21,    created_at: Wed, 02 Nov 2016 02:21:59 UTC +00:00,    updated_at: Wed, 02 Nov 2016 02:21:59 UTC +00:00,    properties: {"123"=>true, "browsed"=>false},    event_type_id: 120,    app_device_manifest_id: 1106>  

if I try to Query it this way. it returns an empty Event::ActiveRecord_Associations_CollectionProxy

app.events.where("properties ->> 'browsed' = ?", "false")  #<Event::ActiveRecord_AssociationRelation:0x3fe48cdaf740>  

I don't want to do things like pluck ids out of the app.events and map it to Event.where query. What would be the best way to get at the events that an app has?

Rails query through multiple models

Posted: 30 Nov 2016 07:49 AM PST

It's been 2 days by now that I'm struggling to write query. So, I'm trying to query within these 3 related models:

class Company...    has_many :programs  end    class Program...    belongs_to :company    has_many   :transactions  end    class Transaction...    belongs_to :program  end  

As output, I need a list of the amount of all Transactions each Company made and on what date.

Upload an attachment to S3 using AWS SDK 2

Posted: 30 Nov 2016 07:16 AM PST

I am using aws-sdk-rails gem over rails 5.0.0.1.

I followed these guides

I am new in RoR so I am getting this error Error

This is my contents_controller.rb file

def create   s3 = Aws::S3::Resource.new(region: 'us-west-2')   file = content_params[:attachment]   puts file.path.split('/').last   obj = s3.bucket(INPUT_BUCKET).object(file)   obj.upload_file(file.path.split('/').last)   @content = Content.new(content_params)   if @content.save    redirect_to contents_path, notice: "The content #{@content.name} has been uploaded."   else    render "new"   end  end  

Do you recommend me using a gem to handle these tasks? In that case, which one?

Disable ruby on rails job for test

Posted: 30 Nov 2016 07:21 AM PST

I'm writing controller test with rspec and after action completed, my job supposed to send email to the admin user. But I'd like to disable this job for my tests or mock it somehow. How can I do this? I'm using delayed_job_active_record+daemons gem.

class AdminNotificationJob < ActiveJob::Base    queue_as :default      def perform(method, parameter)      User.admin.includes(:profile).each do |admin|        AdminMailer.send(method, admin, parameter).deliver_later      end    end  end  

Having different rails and gems versions installed on dev environment

Posted: 30 Nov 2016 07:08 AM PST

I'm quite newbie in ruby and ruby on rails and I'd like some clarification, if possible.

I'm currently having rails 4.2.6 installed on my development environment in which I have built a few projects. Now, for my new projects I'd like to use Rails 5, so I assume that if I type the gem install rails command will get me the latest rails verion and probably set it as default, so every time I want to create a new project by rails new my_new_project_name this project will have the latest version (currently v5).

My question is will my gem list contain both rails versions then or is it going to cause any conflicts and issues to my old porjects? so, if I want to work back on any of my projects which has the "old" version, won't affect of any changes, right? As far as I understand its the bundler who picks the version of each gem, right?

If thats the case, I assume same thing applies and for every other gem that I use for each project, right?

Encrypt Ruby code inside a gem

Posted: 30 Nov 2016 07:06 AM PST

I want to ship out a gem to on premises for clients. I don't want them to know my code so I want to encrypt or obfuscate code inside the .gem file and ship it to them to integrate inside their ruby projects.

Any ref?

LoadError: cannot load such file -- rvm/capistrano

Posted: 30 Nov 2016 07:17 AM PST

I want deploy sinatra project.

Run command cap production deploy.

errors:

cap aborted!  LoadError: cannot load such file -- rvm/capistrano  config/deploy.rb:1:in `require'  config/deploy.rb:1:in `<top (required)>'  /home/user/.rbenv/versions/2.3.1/bin/cap:23:in `load'  /home/user/.rbenv/versions/2.3.1/bin/cap:23:in `<top (required)>'  /home/user/.rbenv/versions/2.3.1/bin/bundle:23:in `load'  /home/user/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'    #gemfile  source 'http://rubygems.org'    gem "rake"  gem "sinatra"  gem "sinatra-activerecord"  gem "sinatra-flash"  gem "pg"  gem "bcrypt"  gem "pry"  gem "pony"  gem "capistrano", '~> 3.1.0'  gem "capistrano-bundler", '~> 1.1.2'  gem "capistrano-rvm", github: "capistrano/rvm"  

Setting capistrano Capgile file

Capfile

# Load DSL and set up stages  require 'capistrano/setup'    # Include default deployment tasks  require 'capistrano/deploy'    # If you are using rvm add these lines:  require 'capistrano/rvm'  set :rvm_type, :user  set :rvm_ruby_version, '2.3.1-p112'  #Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }  

In deploy file i added folowing settng for rvm

#config/deploy.rb  #RVM and bundler settings  set :bundle_cmd, "/home/deploy/.rvm/gems/ruby-2.3.1-p112@global/bin/bundle"  set :bundle_dir, "/home/deploy/.rvm/gems/ruby-2.3.1-p112/gems"  set :rvm_ruby_string, :local  set :rack_env, :production  

I dont undestand why this error, maybe becose First time on local I used rbenv for installing ruby and bundle install gems. But after installed rvm, in directory project select right version ruby with command rvm use 2.3.1.

ruby -v  ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]   

How solve this issue? Thank you for advance.

Where to implement a Linked List Stack in Rails app

Posted: 30 Nov 2016 08:18 AM PST

I am trying to implement a Linked List Stack in my Rails app which is a basic to-do list. But I am not sure where I would place the code for the Linked List within the current Rails App structure. Can someone offer any guidance? Would this go within the Model or the Controller?

Screenshot of Basic to do list app Todolist

Tasks Controller:

class TasksController < ApplicationController     def create     @task = current_user.tasks.build(task_params)       if @task.save       flash[:notice] = "Task created successfully"     else       flash[:error] = "Error creating task"     end       redirect_to current_user   end     def destroy    @task = current_user.tasks.find(params[:id])      if @task.destroy      flash[:notice] = "Task completed successfully"    else      flash[:error] = "Error completing task"    end      redirect_to current_user  end    private    def task_params    params.require(:task).permit(:name)  end  

Show.html.erb file for the tasks created

 <h1>Hello, <%= current_user.email %></h1>     <h2>Create New Task</h2>   <%= form_for [current_user, @task] do |f| %>     <%= f.label :name %>     <%= f.text_field :name %>     <%= f.submit "Create", class: 'btn btn-primary' %>   <% end %>   <h2>Current Tasks</h2>   <% current_user.tasks.each do | task| %>     <p>       <%= task.name %>       <%=link_to [current_user, task], method: :delete do %>         <span class="glyphicon glyphicon-ok"></span>       <% end %>     </p>   <% end %>  

Task.rb(Model)

class Task < ActiveRecord::Base    belongs_to :user  end  

User.rb(Model)

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    has_many :tasks    devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable  end  

The Linkedlist Stack I would like to implement in the Rails App

module LinkedList    class Node      attr_accessor :value, :next_node        def initialize(value, next_node)        @value = value        @next_node = next_node        end      end        class Stack        def initialize          @first = nil        end          def push(value)          @first = Node.new(value, @first)        end          def pop          flash[:notice] = "Task completed successfully" if is_empty?          value = @first.value          @first = @first.next_node          value        end          def is_empty?          @first.nil?        end      end      end  

How do I add a custom predicate-builder in Rails 5?

Posted: 30 Nov 2016 06:37 AM PST

In Rails 4, If I had an ArrayLikeClass class and I wanted to use its objects in where queries like Model.where(id: instance_of_array_like_class), I could do so by registering a predicate-builder:

ActiveRecord::PredicateBuilder.register_handler(ArrayLikeClass, ActiveRecord::PredicateBuilder::ArrayHandler.new)  

after which instances of ArrayLikeClass would behave same as instances of Array when used in where queries.

However, with Rails 5, the API is changed and ActiveRecord::PredicateBuilder::ArrayHandler.new now requires an instance of ActiveRecord::PredicateBuilder. Also register_handler is now an instance method in ActiveRecord::PredicateBuilder.

So, how can I register a predicate-builder handler in Rails 5 for a custom class?

Filterring ActiveRecord Relation...if there are no matches. (Null the active record relation)

Posted: 30 Nov 2016 06:35 AM PST

I have a dashboard that allows for filtering of the results by different parameters. I build methods to filter the results by the given criteria. One area where I'm having trouble is if the previous line should null out the active record relation. Should I just put a bunch of if present? stat

def find_website_stats(options = {})      if options[:date_between].present?        start_date = options[:date_between].split(/-/).first.to_date        end_date = options[:date_between].split(/-/).last.to_date + 1      elsif options[:start_date].present?        start_date = options[:start_date].to_date        end_date = options[:end_date].to_date + 1 if options[:end_date].present?      end        contractor_name = options[:search_contractor] if options[:search_contractor].present?      distributor_name = options[:search_distributor] if options[:search_distributor].present?      distributor_ids = options[:with_distributor] if options[:with_distributor].present?      contractor_ids = options[:with_contractor] if options[:with_contractor].present?      with_country = options[:with_country] if options[:with_country].present?      with_state = options[:with_state] if options[:with_state].present?      search_city = options[:search_city] if options[:search_city].present?        web_stats = self.website_stats        if web_stats.present?        web_stats = web_stats.where(contractor_id: [*contractor_ids]) if contractor_ids.present?        if distributor_ids.present?          web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*distributor_ids]).pluck(:website_stat_id)          web_stats = web_stats.where(id: [*web_stat_ids])        end        web_stats = web_stats.where(date_recorded: start_date..end_date) if start_date.present? && end_date.present?        web_stats = web_stats.with_country(with_country) if with_country.present?        web_stats = web_stats.with_state(with_state) if with_state.present?        web_stats = web_stats.search_city(search_city) if search_city.present?          #untested        if contractor_name.present?          searched_contractor_ids = Brand.search_contractor(contractor_name).pluck(:id)          web_stats = web_stats.where(contractor_id: [*searched_contractor_ids])        end          if distributor_name.present?          searched_distributor_ids = Brand.search_distributor(distributor_name).pluck(:id)          web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*searched_distributor_ids])          web_stats = web_stats.where(id: [*web_stat_ids])        end        

Tuesday, November 29, 2016

rails polymorphic_url destroy action | Fixed issues

rails polymorphic_url destroy action | Fixed issues


rails polymorphic_url destroy action

Posted: 29 Nov 2016 07:43 AM PST

I have some polymorphic_urls which are working ok for actions like new, edit, index, but I need it to destroy action too. Now url's are written like

polymorphic_url [:admin, item], action: :edit, routing_type: :path  

I didn't see in docs anything related to destroy action, if there are possibility to call it somehow?

Unique attribute in has_many association with simple_form

Posted: 29 Nov 2016 07:44 AM PST

I have the following problem I don't know how to solve: ModelA has_many ModelB

ModelB has an bool attribute "default". ModelA must have only one ModelB entry with true "default" attribute. Now, if a new ModelB with "default" set to true is added to ModelA that already contains a ModelB with "default" set to true, the old ModelB will be set to false and the newly added stays true.

I'm using simple_form and cocoon gem to manipulate the data in the views. Thanks for your help!

RSpec - accessing array methods

Posted: 29 Nov 2016 07:36 AM PST

I'm new to testing and struggling with some of the concepts. I understand the idea is to test things in isolation through mocks and stubs, however am struggling with the following:

class Circle    has_many :jobs      def accepted      jobs.where('sitter_id > 0')    end  end    class Job    belongs_to :circle  end  

And my RSpec:

require 'rails_helper'    RSpec.describe Circle, type: :model, focus: true do      let (:circle_1) { FactoryGirl.create(:circle, title: 'London',                                                  location: 'London',                                                  administrator_id: 1) }      let (:job_1) { FactoryGirl.create(:job, start_time: "2016-11-14 20:00:00",                                            end_time: "2016-11-14 23:00:00",                                            tokens_offered: 6,                                            requester_id: 1,                                            circle_id: 1,                                            sitter_id: 5,                                            actual_start_time: "2016-11-14 20:00:00",                                            actual_end_time: "2016-11-14 23:30:00",                                            tokens_paid: 7) }      before do      circle_1.stub(:jobs).and_return([job_1])    end      describe 'instance methods' do      context 'accepted' do         it 'should return jobs with a sitter' do           expect(circle_1.accepted).to include(job_1)        end      end    end  end  

This results in:

NoMethodError:     undefined method `where' for #<Array:0x007feb4ae72858>  

Would I then stub the behaviour of the where method on the array? What I'm confused by is surely that's exactly what I'm testing, and by stubbing it I'm basically telling the test what the code does rather than testing the code itself?

If someone could explain if I'm understanding this wrong, and either way how I can either rewrite the test or get it to pass, it would be greatly appreciated.

Iterate through array of arrays and pass coordinates to google map

Posted: 29 Nov 2016 07:27 AM PST

In my Rails app I have google map that I want to display pins based on coordinates (latitude, longitude). I have dummy data in user.rb file as an array and I'm trying to map through it and pass coordinates to google map, however I'm missing something basic, because all works if I supply it manually. So how do I iterate so coordinates would be displayed on map?

#user.rb    class User < ApplicationRecord      COORDINATES = [[51.50853, -0.076132], [51.510357, -0.116773]]      def self.latitude      COORDINATES.map do |x|        x[0] # How to pass coordinates correctly?      end    end      def self.longitude      COORDINATES.map do |x|        x[-1] # How to pass coordinates correctly?      end    end  end  

That's User controller index action:

def index    @latitude = User.latitude    @longitude = User.longitude  end  

And that's index.html.erb. Here I provide @latitude and @longitude.

handler = Gmaps.build('Google');  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){  markers = handler.addMarkers([    {      "lat": <%= @latitude %>,      "lng": <%= @longitude %>    }  ]);  });  

Get next and previous versions for a version id using paper_trail

Posted: 29 Nov 2016 07:14 AM PST

I'm using the paper trail gem to version my Pages model.

I have a method called version which takes a page_id and version_id.

def version    page = Page.where(id: params[:page_id]).first    @version = page.versions.where(id: params[:version_id]).first    @previous_version = @version.previous_version rescue nil    @next_version = @version.next_version rescue nil  end  

What I want to do is get the next and previous versions to pass them to my view. However I can only access the current version. @previous_version and @next_version are always nil even though I have next and previous versions. It seems it doesn't know what the methods previous_version and next_version are.

Getting all the hashes in an array for which one key matches

Posted: 29 Nov 2016 06:54 AM PST

I have an array of hashes with the same keys and I want to get all the hash for which the value of one is same.

Eg : [{:a => 1, :b => 2, :c => 5}, {:a => 1, :b => 4, :c => 15}, {:a => 12, :b => 2, :c => 6}]

Result : [{:a => 1, :b => 2, :c => 5}, {:a => 1, :b => 4, :c => 15}]

hash = [{:a => 1, :b => 2, :c => 5}, {:a => 1, :b => 4, :c => 15}, {:a => 12, :b => 2, :c => 6}]   hash.select {|k| k[:a] = 1}   

Thanks in advance.

Restrict file upload of html.erb file

Posted: 29 Nov 2016 06:49 AM PST

How do I restrict a file upload input field so that only html.erb files are accepted?

I have an input field like the following:

<%= f.input :upload_field, as: :file, label: false %>  

I know the accept setting can control this inside an input_html tag but I am not sure how to implement it correctly.

SSL Certificate from RapidSSL with Heroku and CloudFront

Posted: 29 Nov 2016 06:35 AM PST

I missed the end date of my SSL certificate few days ago but I did buy the renew last month. My app runs with Ruby on Rails using Heroku and CloudFront for the assets. My SSL certificate come from RapidSSL.

Here is the process I did:

  • I got the RapiddSSL key by email that i store in a crt file
  • I ran the Heroku command line heroku certs:update cert.crt server.key -- app remote production

The command line heroku certs --app remote production results with a trusted status but when I open the URL browsers warns about that untrusted certificate.

At the same time none of application assets stored on CloudFront are available (net::ERR_INSECURE_RESPONSE). I asked for help on Heroku assistance, they told me that the SSL certificate for the app is OK but it's seems to need an update for assets certificate.

So I went to AWS console in aim to find CloudFront SSL configuration, I ended on ACM console page to give the RapidSSL certificate to resolve the problem but I cannot be sure to take the right files to do this.

What I need is to solve the access to the website and to the associated assets to ensure trust of my customers. What did I wrong? Am I missing something?

Thanks for any help you can provide!

Devise subdomains - from www.appname.com/admin/login to admin.appname.com/login

Posted: 29 Nov 2016 06:35 AM PST

I have two Devise models: users and admins.

Current my routes to admins are:

Rails.application.routes.draw do    devise_for :admins, path: 'admin', path_names: { sign_in: 'login', sign_out: 'logout'}  end  

I want to change from www.appname.com/admin/login to admin.appname.com/login

How can I achieve this?

rails active record association, fill up foreign key using build from console

Posted: 29 Nov 2016 06:13 AM PST

I'm building a very simple rails association and testing it through console. I have a User model and a Courses model. These are associated in the following way:

class User < ApplicationRecord      has_many :courses, :dependent => :destroy  end    class Course < ApplicationRecord      belongs_to :teacher, :foreign_key => 'teacher_id', :class_name => 'User'  end  

When testing through console I need to have a user_id column in the courses table in order to run

User.first.courses.build  

However, doing that I am left with an empty teacher_id in the courses table.

I would like to know if it is possible to have only a teacher_id column in the courses table (no user_id which seems to me redundant) and to fill it up automatically running

User.first.courses.build  

Relationship Models

Posted: 29 Nov 2016 06:02 AM PST

I'm fairly new to rails and I'm having trouble with some Model Relationships.

I have these tables

+--------------+-----------------+------+  | Artists      | Artist Features | Tags |  +--------------+-----------------+------+  | ID           | ID              | ID   |  | Name         | artist_id       | name |  | Address      | price           |      |  | Country      | tag_id          |      |  | Email        |                 |      |  +--------------+-----------------+------+  

I have relationships between Artists and Artist Features artists has_many artist_features and artist_features has_many tags. I want to, with a query get all Artists, features and tags based on the structure above, artist_id and tag_id

I've used the below to get the artists and the corresponding artist_features but would like to also get the tags too based on the tag_id

@Artists = Artist.all.artist_features  

How to use joint query in this association - Ruby on Rails

Posted: 29 Nov 2016 06:20 AM PST

I am working in ruby 2.1.5 and rails 3.2.1. I want to list all the company in grid which is associated to company_name = John

Company table:

enter image description here

company model:

has_many :partner_relationships, :class_name => "CompanyRelationship",:foreign_key => 'partner_id',  

company_relationships table:

enter image description here

I want to get all the company information from company table where company.id = partner_id. I tried the below query

Company.joins(:partner_relationships).where('company_relationships.partner_id' => company.id)  

This is returning 3 set of same data that is <#id:2, company_name:John, description:I am John#>

I want to return the records as follows <#id:1, company_name:Jose, description:I am Jose#>, <#id:3, company_name:George, description:I am George#>,..<#id:5, company_name:Alwin, description:''#>

Please help me in solving this.

Devise user to create profile based on role_type after devise sign_up

Posted: 29 Nov 2016 06:37 AM PST

I'm new to Rails and building a job-board marketplace.I'm stuck with a user signup profile form. I'm using devise(4.2) and I liked the idea suggested below by @richard peck where he suggests to create profile before user_create and then just redirect to profile view and update users table with registration form. Building User profile based on Devise

My signup is a 2-way process. step 1 - devise sign-up form with just an extra field to check role of user as user(jobseeker)or company. Step 2 - Using this role, create separate profile forms for users and company. If role is not committed to DB, then user also should not be saved and again user sign_up must happen.

At present, I'm trying with just one generic user form which has fields first_name and last_name. I used before_create :build_profile in user model which creates a blank profile and user. Now, I want after sign_up to be redirected to profile page to add first and last names and this data be updated to the blank profile just created for that user. So I've overwritten after_sign_up_path_for in my registrations_controller to redirect to profile form but it doesn't redirect at all.

Can someone provide sample code as I've tried several ways and even if I create profile separately, the mapping of user to its profile is not successful? I using Devise with Rails 5.

The error I'm getting is:UrlGenerationError in RegistrationsController#create.

routes.rb

Rails.application.routes.draw do    mount RailsAdmin::Engine => '/admin', as: 'rails_admin'    root "jobs#index"    devise_for :users, :controllers => {:omniauth_callbacks => "users/omniauth_callbacks", registrations: "registrations"}    resources :users do      # nested resource for job_applications      resources :job_applications, only: [:show, :index]      resources :profiles, only: [:show, :update]    end    resources :jobs, :categories, :job_applications    get '/dashboard' => 'jobs#dashboard'  end  

reg_con

class RegistrationsController < Devise::RegistrationsController      protected      def after_sign_up_path_for(resource)        #request.env['omniauth.origin'] || user_profile_path          if resource.class == RailsAdmin          rails_admin_path        elsif resource.class == User && current_user.role == 'user'          user_profile_path        else # to check for company user resource.class == User && current_user.role == 'company'          puts "redirecting to company profile"        end      end    end  

profiles_controller.rb

      class ProfilesController < ApplicationController          def show        end          def update          @profile = Profile.find_by_user_id(profile_params)          current_user.update(@profile)        end          def destroy          @profile.destroy          respond_with(@profile)        end          private          def profile_params          params.require(:user).permit(profile_attributes: [])        end          def set_profile          @profile = Profile.find(params[:id])        end      end  

profile.rb

class Profile < ApplicationRecord    belongs_to :user  end  

user.rb

   class User < ApplicationRecord        include Gravtastic gravtastic        after_initialize :set_default_role        before_create :build_profile        devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable        devise :omniauthable, :omniauth_providers => [:facebook]        enum role: [:user, :company, :admin]        has_many :jobs, :foreign_key => 'company_id', :dependent => :destroy        has_many :job_applications        has_one :profile          def self.from_omniauth(auth)          where(provider: auth.provider, uid: auth.uid).first_or_create do |user|            user.email = auth.info.email            user.password = Devise.friendly_token[0, 20]          end        end          def build_profile          Profile.create          true        end          def set_default_role          self.role ||= :user        end  

How can i add a method to an existing class in Rails 5?

Posted: 29 Nov 2016 04:44 AM PST

Sorry for my bad english. I have to add a method in Date class in Rails because i want to use my translated day names. So, i tried:

class Date    def date_of_next(day)      date  = Date.parse(day)      delta = date > Date.today ? 0 : 7      date + delta    end  end  

in config/initializers/date_of_next.rb but when i call Date.date_of_next(day) in my controller i get "no method in Date". How can i do that? And where should i put the file?

Why does the second 'delete :destroy' in this spec not run?

Posted: 29 Nov 2016 05:45 AM PST

I have a spec that is giving unexpected results. I've not been able to track down the cause. Can anyone help point me in the right direction?

let(:object1) { create :object }  let(:object2) { create :object }  let(:user)    { create :user }  describe "DELETE #destroy" do    before :each do      Rails.logger.info "Object 1 ID: #{object1.id}"      Rails.logger.info "Object 2 ID: #{object4.id}"      user.roles.push Role.where(name: 'FullAccess').first      sign_in user      delete :destroy, {:id => object1.to_param}    end    it {       expect {         delete :destroy, {:id => object2.to_param}       }.to change(Object, :count).by(-1)    }  end   

Results in

Failure/Error:    expect {      delete :destroy, {:id => object2.to_param}    }.to change(Object, :count).by(-1)  expected #count to have changed by -1, but was changed by 0  

But if I comment out delete in the before block, the test passes.

before :each do    sign_in user    # delete :destroy, {:id => office1.to_param}  end  

Why would the second object not be deleted?

edit

The method being tested is

def ObjectController < ApplicationController    load_and_authorize_resource    def destroy      Rails.logger.info "DELETE OBJECT ID: #{@object.id}"       @object.destroy      respond_to do |format|        format.html { redirect_to objects_url, notice: t('.notice') }        format.json { head :no_content }      end    end  end  

Edit 2

Added logging codes to the examples above. The log output now includes

Object 1 ID: 1  Object 2 ID: 2  DELETE OBJECT ID: 1   DELETE OBJECT ID: 1   

Ruby Multiple Image Uplaod

Posted: 29 Nov 2016 03:55 AM PST

I have a ruby function which uploads images to AWS. At a time user selects about 200 images. I want to run this function inside a thread. Then the user uploads another set of images. In this process some of the images are not uploading. Is it an issue to upload bulk images inside threads?

Bootstrap date-picker calendar issue

Posted: 29 Nov 2016 03:58 AM PST

I am using Bootstrap date-picker to select mm/dd/yyyy, and seeing wired behavior with calendar enter image description here

some of the next month day's value is encountered in current month calendar. I have tried with css background color and z-index properties but didn't succeed.

When I inspect it in the developer tools I see two tr with:

<tr>     <td class="day disabled">27</td>     <td class="day disabled">28</td>     <td class="day">29</td>     <td class="day">30</td>     <td class="day new">1</td>     <td class="day new">2</td>     <td class="day new">3</td>   </tr>  <tr>    <td class="day new">4</td>    <td class="day new">5</td>    <td class="day new">6</td>    <td class="day new">7</td>    <td class="day new">8</td>    <td class="day new">9</td>    <td class="day new">10</td>  </tr>  

which are causing the overlapping.

Rails Rspec IntegrationTest Capybara

Posted: 29 Nov 2016 07:42 AM PST

I have started to test my app via Rspec (Capybara). This is how I am doing it:

require 'rails_helper'  RSpec.describe "Homepages", type: :request do    describe "GET / without login" , js: true do      before(:all) do         Employee.create(username: "username", password: "12345", password_confirmation: "12345")      end      it "works!" do        visit root_path        fill_in "loginname", with: "username"        fill_in "password", with: "12345"        click_button('sign_in')      end    end  end  

Because of env namely "TEST-ENV" I have to create an employee at first. the problem is, if I run 'rake spec:requests', I get this errors:

1) Homepages GET / without login works!   Got 0 failures and 2 other errors:     1.1) Failure/Error:          def initialize(template, original_exception)            super(original_exception.message)            @template, @original_exception = template, original_exception            @sub_templates = nil            set_backtrace(original_exception.backtrace)          end          ArgumentError:          wrong number of arguments (1 for 2)         #/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.7/lib/action_view/template/error.rb:64:in `initialize'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/session.rb:128:in `exception'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/session.rb:128:in `raise'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/session.rb:128:in `rescue in raise_server_error!'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/session.rb:125:in `raise_server_error!'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/session.rb:113:in `reset!'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara.rb:334:in `block in reset_sessions!'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara.rb:334:in `reverse_each'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara.rb:334:in `reset_sessions!'       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/rspec.rb:21:in `block (2 levels) in <top (required)>'       # ------------------       # --- Caused by: ---       # Capybara::CapybaraError:       #   Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true       # /.rvm/gems/ruby-2.1.1/gems/capybara-2.10.1/lib/capybara/session.rb:126:in `raise_server_error!'  

rails : association tabel (has_and_belongs_to_many) not save any record

Posted: 29 Nov 2016 03:37 AM PST

i use rails 5 , simple form. in my app there is a Category model and there is a OnlineProduct model. i dont know why when i want to add some categories to my OnlineProduct association table remain empty and don't change.

Category model:

class Category < ApplicationRecord      has_ancestry      has_and_belongs_to_many :internet_products    end  

InternetProduct model:

class InternetProduct < ApplicationRecord    belongs_to :user    belongs_to :business    has_and_belongs_to_many :categories  end  

InternetProduct controller:

  def new       @internet_product = InternetProduct.new    end    def create       @internet_product = InternetProduct.new(internet_product_params)         respond_to do |format|          if @internet_product.save             format.html { redirect_to @internet_product, notice: 'Internet product was successfully created.' }             format.json { render :show, status: :created, location: @internet_product }          else              format.html { render :new }              format.json { render json: @internet_product.errors, status: :unprocessable_entity }          end       end    end  private:  def internet_product_params    params.require(:internet_product).permit(:name, :description, :mainpic, :terms_of_use,                                         :real_price, :price_discount, :percent_discount,                                         :start_date, :expire_date, :couponـlimitation, :slung,                                         :title, :meta_data, :meta_keyword, :enability, :status,                                         :like, :free_delivery, :garanty, :waranty, :money_back,                                         :user_id, :business_id,                                         categoriesـattributes: [:id, :title])  end  

and in the view only the part of who relate to categories :

   <%= f.association :categories %>  

all the categories list in view (form) but when i select some of them not save in database. in rails console i do this

 p = InternetProduct.find(5)   p.categories = Category.find(1,2,3)  

this save to database without any problem, what should i do ? tanks for reading this

Ruby compass - cannot load such file -- compass/core (LoadError)

Posted: 29 Nov 2016 05:05 AM PST

I'm trying to install and work around compass gem and the commands I used while installing this are -

gem install sass  gem install compass  

Now I can see the version of sass with the command -

sass --version  

But when I do -

compass --version  

The messsage i get is -

/home/name/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- compass/core (LoadError)  from /home/name/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/compass-1.0.3/lib/compass.rb:14:in `block in <top (required)>'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/compass-1.0.3/lib/compass.rb:13:in `each'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/compass-1.0.3/lib/compass.rb:13:in `<top (required)>'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/compass-1.0.3/bin/compass:20:in `block in <top (required)>'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/compass-1.0.3/bin/compass:8:in `fallback_load_path'  from /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/compass-1.0.3/bin/compass:19:in `<top (required)>'  from /home/name/.rbenv/versions/2.3.1/bin/compass:22:in `load'  from /home/name/.rbenv/versions/2.3.1/bin/compass:22:in `<main>'  

I've tried searching on google and went through whole lot of github issues and stackoverflow questions regarding compass, but any of those didn't help.

How should i resolve this issue?

Update:- I was asked to include the o/p of following command here -

gem list -d | grep compass -A 4  

O/p:-

    compass (1.0.3)      Authors: Chris Eppstein, Scott Davis, Eric M. Suzanne, Brandon      Mathis, Nico Hagenburger      Homepage: http://compass-style.org      Installed at: /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0        A Real Stylesheet Framework    compass-core (1.0.3)      Authors: Chris Eppstein, Scott Davis, Eric M. Suzanne, Brandon      Mathis      Homepage: http://compass-style.org/reference/compass/      License: MIT      Installed at: /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0        The Compass core stylesheet library  --  compass-import-once (1.0.5)      Author: Chris Eppstein      Homepage:      https://github.com/chriseppstein/compass/tree/master/import-once      License: MIT      Installed at: /home/name/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0        Speed up your Sass compilation by making @import only import each  

`rake db:seed:shop:curtain` fail with “Don't know how to build task 'db:seed:shop:curtain'”?

Posted: 29 Nov 2016 03:04 AM PST

ruby 2.1.5, rails 4.2, rake

installed gem "seedbank" seedbank (0.3.0)

I have following structure: seeds/shop/curtain/

I want run all seed files from folder curtain

rake db:seed:shop:curtain  

rake aborted! Don't know how to build task 'db:seed:shop:curtain'

What wrong, explain me please. Thank you

Read the JSON array value in the rails controller

Posted: 29 Nov 2016 03:21 AM PST

I have try to getting the params via post method

POST /api/test HTTP/1.1  Host: localhost:3000  Content-Type: application/json  Cache-Control: no-cache  Postman-Token: 945ce038-4bf1-ed50-afcb-cc715cf3a3fc    {      "service_requests": [{"service_id":2},{"service_id" : 3}]  }  

In the controller I have test with a method and print like this. But I could not able to print this. How do I print all the values in for each or for loop from this Json Array of JSON Objects

def test     render :html => params[:service_requests][0].service_id  end  

Javascript : make request again when accessing previous state

Posted: 29 Nov 2016 02:25 AM PST

I use this in my JS:

window.history.replaceState({url: , scrollTop: wTop}, 'foo', 'bar');  

But when I go to another page from here then press the back button, I end up not firing a request. Instead, my browser loads everything back from its "disk cache". I'd like to fire the request again, since my state has change and it should ask for the corrected page. How can I achieve that?

I tried with this in my rails controller:

response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'  response.headers['Pragma'] = 'no-cache'  response.headers['Expires'] = '0'  

But apparently, the history list is not entirely related to the cache feature.

Nested Forms In rails Using cocoon Gem

Posted: 29 Nov 2016 02:38 AM PST

For Nested forms in rails, I used cocoon gem.

I included

gem 'cocoon' in gem file

and

'require cocoon' in application.js

file.

In output am getting nested forms but the values which is am giving is not stored in the backend(mysql)?? kindly help me..!

My Controller as follows

    class SubjectsController < ApplicationController    load_and_authorize_resource    before_action :set_subject, only: [:show, :edit, :update, :destroy]      def index      @subjects = Subject.where("org_id = ?", current_user.org_id)    end      def new      @subject = Subject.new      @subject.subject_modules.build      getStandard_lists    end      def create      @subject = Subject.new(subject_params)      @subject.org_id = current_user.org_id      @subject.created_by = current_user.username      respond_to do |format|        if @subject.save          format.html { redirect_to @subject and flash[:notice] = 'Subject created successfully.' }        else          getStandard_lists          format.html { render :new }        end      end    end      def edit    getStandard_lists    end      def update       @subject.updated_by = current_user.username       respond_to do |format|         if @subject.update(subject_params)           format.html { redirect_to @subject and flash[:notice] = 'Subject updated successfully.'}         else           getStandard_lists           render :edit         end       end    end     def getStandard_lists     @standard_list = Standard.select("standard_id,standard_name")                              .where("org_id = ?",current_user.org_id)                              .order("standard_order")   end     def assignStandard       @subject = Subject.find(params[:subject_id])       @subject_module = SubjectModule.new       @subject_module.standard_id = params[:standard][:standard_id]     @subject_module.subject_id = params[:subject_id]       respond_to do |format|       if @subject_module.save         format.html { redirect_to @subject and flash[:notice] = 'Standard assigned successfully.' }       else         format.html { redirect_to @subject and flash[:notice] = 'Standard not assigned.' }       end     end     end    def standard_module_detail    @standard = Standard.find(params[:standard_id])    end      private      # Use callbacks to share common setup or constraints between actions.      def set_subject        @subject = Subject.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def subject_params         params.require(:subject).permit(:id, :org_id, :subject_id, :subject_name, :subject_desc,                                 :subject_color, subject_modules_attributes: [:id, :org_id, :created_by, :subject_module_id, :subject_id,                                 :module_number, :module_name, :_destroy, module_details_attributes: [:id, :module_detail_id, :subject_module_id,                                  :module_detail_number, :description, :_destroy]])     end  end  

and my model as follows

    class Subject < ActiveRecord::Base    validates :subject_name, :presence=>{:message=>" cannot be blank"},                   :length=>{:maximum => 50, :message=>"should not be greater than 50 characters"},                   :format => { :with => /\A[a-zA-Z0-9@_\.\-\+\s]*\z/, :message => "may only contain letters."},                   :uniqueness=> { scope: :org_id }                   has_many :subject_modules, dependent: :destroy                   accepts_nested_attributes_for :subject_modules, reject_if: :all_blank, allow_destroy: true  end      class SubjectModule < ActiveRecord::Base    belongs_to :subject    has_many :module_details,  dependent: :destroy    accepts_nested_attributes_for :module_details, reject_if: :all_blank, allow_destroy: true  end      class ModuleDetail < ActiveRecord::Base    belongs_to :subject_module  end  

How does "render template" works inside a controller?

Posted: 29 Nov 2016 06:43 AM PST

I created an article scaffold inside a namespace named 'admin', but because the visitors can't access the 'admin' part, I'm trying to render the view of the scaffold in a public controller, home#blog, so that the creation, the editing and the suppression of an article is made inside the admin part, but you can read the said article in the public part of the website

However, after adding render template: 'home/blog' it doesn't seem to work, I still get redirected to admin/articles/<id>, but maybe I forgot to do something else or maybe I did something wrong

Here's my article controller:

class Admin::ArticlesController < ApplicationController    before_action :set_admin_article, only: [:show, :edit, :update, :destroy]      layout 'admin'      # GET /admin/articles    def index      @admin_articles = Admin::Article.all    end      # GET /admin/articles/1    def show      render template: 'home/blog'    end      # GET /admin/articles/new    def new      @admin_article = Admin::Article.new    end      # GET /admin/articles/1/edit    def edit    end      # POST /admin/articles    def create      @admin_article = Admin::Article.new(admin_article_params)      @admin_article.user = current_user      if @admin_article.save        redirect_to @admin_article, notice: 'Article was successfully created.'      else        render :new      end    end      # PATCH/PUT /admin/articles/1    def update      if @admin_article.update(admin_article_params)        redirect_to @admin_article, notice: 'Article was successfully updated.'      else        render :edit      end    end      # DELETE /admin/articles/1    def destroy      @admin_article.destroy      redirect_to admin_articles_url, notice: 'Article was successfully destroyed.'    end      private      # Use callbacks to share common setup or constraints between actions.      def set_admin_article        @admin_article = Admin::Article.friendly.find(params[:id])      end        # Only allow a trusted parameter "white list" through.      def admin_article_params        params.require(:admin_article).permit(:titre, :contenu)      end  end  

What did I miss?

Don't hesitate to ask for more details

Thank you in advance

Rails custom model method

Posted: 29 Nov 2016 03:13 AM PST

I have model user and I want create in model some method, call this method in helper, in controller Lists example and call this helper in view, but have error and don't know how to right write

my model User and my method

  def include_current_user      User.where.not(id: current_user.id)    end  

my controller Lists and helper

  def shared_users      @users ||= User.include_current_user    end      helper_method :shared_users  

and my views where call helper

  <%= f.collection_check_boxes(:users, shared_users, :id, :email)%>  

heave error

undefined method `include_current_user' for #<Class:0x007f389c649f98>  Did you mean?  included_modules  

when I moved my method to self part like this:

  class << self        def include_current_user        where.not(id: current_user.id)      end    end  

have error

undefined local variable or method `current_user' for #<Class:0x007f38ac5d98c8>  Did you mean?  current_scope  

current user this is helper in ssesion helper

  def current_user      if (user_id = session[:user_id])        @current_user ||= User.find_by(id: user_id)      elsif (user_id = cookies.signed[:user_id])        user = User.find_by(id: user_id)        if user && user.authenticated?(cookies[:remember_token])          log_in user          @current_user = user        end      end    end  

maybe nned add variable for my method include_current_user and get in action call like this

  def shared_users      @users ||= User.include_current_user(current_user)    end  

and method in model

  class << self        def include_current_user(user)        where.not(id: user.id)      end    end  

when created some query in action everything fine, like this

  def shared_users      @users ||= User.where.not(id: current_user.id)    end      helper_method :shared_users  

But I want create method in model, mayde more complicated, how do right way ?

Rails has_many through save fail

Posted: 29 Nov 2016 03:57 AM PST

I've tried to save my model, but failed to save it.

 #starship.rb     class Starship < ApplicationRecord      has_many :crew_members,inverse_of: :starship      accepts_nested_attributes_for :crew_members        has_many :holodeck_programs,inverse_of: :starship      accepts_nested_attributes_for :holodeck_programs   end  

 #crew_member.rb     class CrewMember < ApplicationRecord     belongs_to  :starship     accepts_nested_attributes_for :starship     has_many :holodeck_programs,through: :starship   end  

 #holodeck_program.rb     class HolodeckProgram < ApplicationRecord     belongs_to :starship     belongs_to :crew_member   end  

#controller    def create    #Starship,CrewMember and HolodeckProgram are new via CrewMember.new    @crew_member = CrewMember.new(crew_member_params)    @crew_member.save    .    .  end    .    .  private   def crew_member_params    params.require(:crew_member).permit(:name,:division,:starship_id,    starship_attributes: [:name,:id,    holodeck_programs_attributes: [:title,:starship_id,:crew_member_id]])   end  

Because there is no crew_member_id in holodeck_programs_attributes, validation error happen.

I can not use inverse_of: :crew_member because of through in crew_member.rb

How can I handle it?

application.html.haml not rendering on other views

Posted: 29 Nov 2016 01:39 AM PST

I am using

rails 4.2.1 haml-rails jquery.turbolinks

application.html.haml is working fine on root but when I redirect to other view, application layout is not getting rendered because of which jquery is not working.

I have made sure all my controllers inherit from ApplicationController class and application_controller inherits ActionController::Base

application.js

//= require jquery  //= require jquery.turbolinks  //= require jquery_ujs  //= require bootstrap-sprockets  //= require jquery.minicolors  //= require light-gallery  //= require turbolinks  //= require jquery.easing  

application.html.haml

!!!  %html    %head      %meta{:content => 'text/html; charset=UTF-8', 'http-equiv' => 'Content-Type'}/      %title CmsBuilder      = stylesheet_link_tag    'application', media: 'all'      = javascript_include_tag 'application'      = csrf_meta_tags    %body      = render partial: 'layouts/header'      = yield  

Difference between selenium and capybara at Ruby on rails Testing?

Posted: 29 Nov 2016 06:28 AM PST

Selenium - Testing Framework
Capybara - Ruby Integration Testing Tool

Could anyone explain, what is the actual difference Selenium and Capybara in terms of Ruby on Rails automation testing?

Server side image caching with Cache-Control header value of no-cache

Posted: 29 Nov 2016 01:11 AM PST

Due to Gmail's insatiable desire to cache everything under the sun, in order to get some dynamic images to show I need to set the 'Cache-Control' header to 'no-cache'.

There's about 8mb of images in total.

Each email open is likely to result in about 20 requests. Estimated open count of about 500,000 people. So that's a fair few requests.

My question is is there a way I could harness some sort of server-side cache, whilst disabling the client-side caching, in such a way that would allow me to handle a reasonable number of concurrent requests?