Question

I have models

class Profile < ActiveRecord::Base
  belongs_to :user
  has_many :user_interests
  has_many :interests, :through => :user_interests
  accepts_nested_attributes_for :user_interests
end

class UserInterest < ActiveRecord::Base
  belongs_to :profile
  belongs_to :interest
end

class Interest < ActiveRecord::Base
  has_many :user_interests
  has_many :profiles, :through => :user_interests
end

controller

private
    def profile_params
      params.require(:profile).permit(:first_name, :last_name, :date_of_birth, user_interests_attributes: {:interest => []})
    end

view

=#"http://stackoverflow.com/questions/18428871/multi-column-forms-with-fieldsets"
= simple_form_for(@profile, html: {class: 'form-horizontal'}) do |f|
  .well.well-lg
    %fieldset
      %legend Personal Information
      .row
        .col-sm-4
          .form-group
            = f.input :first_name, label: 'First Name*'
            = f.hint 'No special characters, please!'
        .col-sm-4
          .form-group
            = f.input :last_name, label: 'First Name*'
            = f.hint 'No special characters, please!'
      .row
        .col-sm-4
          .form-group
            = f.input :date_of_birth, as: :string, 'data-behaviour'=>'datepicker'
      %legend Other Information
      .row
        .col-sm-4
          .form-group
            = f.simple_fields_for :user_interests, UserInterest.new do |s|
              = s.collection_select(:interest, Interest.all, :id, :name,{},{:multiple=>true})
            = f.hint 'Please use Ctrl key on your keyboard to select multiple items'
      .row
        = f.submit
      

But getting error unpermitted parameters

profile_params

Unpermitted parameters: interest

=> {"first_name"=>"", "last_name"=>"", "date_of_birth"=>"", "user_interests_attributes"=>{"0"=>{}}}

where my params are:

params => {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"7/7sKljbi88cmUOen/WFWzhzV6exE8I8fBnNMA5EELw=", "profile"=> {"first_name"=>"", "last_name"=>"",
"date_of_birth"=>"",
"user_interests_attributes"=>{"0"=>{"interest"=>"test"}}}, "commit"=>"Update Profile", "action"=>"update", "controller"=>"profiles", "id"=>"1"}

Please correct me where I am wrong

Was it helpful?

Solution

You forgot to add accepts_nested_attributes_for :interest on UserInterest.

class Profile < ActiveRecord::Base
  belongs_to :user
  has_many :user_interests
  has_many :interests, :through => :user_interests
  accepts_nested_attributes_for :user_interests
end

class UserInterest < ActiveRecord::Base
  belongs_to :profile
  belongs_to :interest
  accepts_nested_attributes_for :interest
end

class Interest < ActiveRecord::Base
  has_many :user_interests
  has_many :profiles, :through => :user_interests
end

You might have to define interest as a valid parameter on strong_parameters definition in your controller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top