2014-02-20 48 views
1

我有機型nested_attributes與simple_field_for獲取未經許可的參數錯誤軌道

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

未經許可的參數:興趣

=> { 「first_name的」=> 「」, 「姓氏」=> 「」, 「DATE_OF_BIRTH」=> 「」, 「user_interests_attributes」=> {」 0 「=> {}}}

在我的PARAMS是:

PARAMS => {」 UTF8 「=>」 ✓ 「 」_method「=> 」補丁「,」 authenticity_token 「=>」 7/7sKljbi88cmUOen/WFWzhzV6exE8I8fBnNMA5EEL 「=」, 「profile」=> {「first_name」=>「」,「last_name」=>「」,
「date_of_birth」=>「」,
「user_interests_attributes」=> {「0」=> {「interest」=>「test」}}}, 「commit」=>「Update Profile」,「action」=>「update」, 「controller」=>「profiles」,「id」=>「1 「}

請糾正我在哪裏,我錯了

回答

1

你忘了對使用者興趣增加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定義的有效參數。