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?

No comments:

Post a Comment