nested_attributes with simple_field_for获取未经许可的参数错误轨道

时间:2014-02-20 04:36:05

标签: ruby-on-rails ruby-on-rails-4 nested-attributes

我有模特

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

视图

=#"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

但是获取错误未允许的参数

  

profile_params

     

未经许可的参数:兴趣

     

=&GT; {“first_name”=&gt;“”,“last_name”=&gt;“”,“date_of_birth”=&gt;“”,“user_interests_attributes”=&gt; {“0”=&gt; {}}}

我的参数是:

  

PARAMS   =&GT; {“utf8”=&gt;“✓”,“_ method”=&gt;“patch”,“authenticity_token”=&gt;“7 / 7sKljbi88cmUOen / WFWzhzV6exE8I8fBnNMA5EELw =”,   “简档”=&GT; {“first_name”=&gt;“”,“last_name”=&gt;“”,
  “DATE_OF_BIRTH”=&gt; “中”,
  “user_interests_attributes”=&GT; { “0”=&GT; { “兴趣”=&gt; “中测试”}}},   “commit”=&gt;“更新个人资料”,“行动”=&gt;“更新”,   “controller”=&gt;“profiles”,“id”=&gt;“1”}

请纠正我错在哪里

1 个答案:

答案 0 :(得分:1)

您忘记在UserInterest上添加accepts_nested_attributes_for :interest

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

您可能必须将兴趣定义为控制器中strong_parameters定义的有效参数。