2012-11-07 56 views
0

我有廣告系列和消息。廣告系列包含許多屬於廣告系列的訊息和訊息。我爲模型設置嵌套屬性,並在我看來,我試圖創建一個與模型相關的消息。下面的代碼:嵌套屬性的另一個質量分配問題

class Campaign < ActiveRecord::Base 
    attr_accessible :message_id, :name, :group_id, :user_id, :messages_attributes 

    has_many :messages 
    belongs_to :group 
    belongs_to :user 

    accepts_nested_attributes_for :messages 
end 

class Message < ActiveRecord::Base 
    attr_accessible :body, :sent, :sent_at 

    belongs_to :user 
    belongs_to :campaign 
    has_many :responses 

end 

和形式:

= form_for @campaign, :html => {:class => 'form-horizontal'} do |f| 
...removed error output code... 
    %legend 
    Enter the campaign information 
    .field 
    .control-group 
     %label.control-label 
     Campaign Name 
     .controls 
     = f.text_field :name 
     = f.collection_select(:group_id, current_user.groups.all, :id, :name, :include_blank => true) 
     = f.fields_for :message do |m| 
      = m.text_area :body, :rows => 3 
     .form-actions= f.submit "#{params[:action] == 'new' ? 'Create New Campaign' : 'Save Campaign'}", :class => 'btn btn-success' 

我知道這可能是很簡單的東西,但我不斷收到以消息的質量分配問題。這裏的錯誤:

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: message): 
    app/controllers/campaigns_controller.rb:18:in `update' 

終於PARAMS是那些獲得從表單創建:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"(removed)", "campaign"=>{"name"=>"Weekly Poker", "group_id"=>"1", "message"=>{"body"=>"s"}}, "commit"=>"Save Campaign", "id"=>"1"} 
+0

它應該是'= f.fields_for:messages do | m |',複數。 – veritas1

+0

@ veritas1我曾嘗試過,然後頁面上的文本框消失...真的很奇怪。任何想法爲什麼會發生? –

+1

你的控制器裏有'@ campaign.messages.build'嗎? – veritas1

回答

0

因爲它是一個has_many協會應該是複數形式:

= f.fields_for :messages do |m| 

而且,在控制器中,您將需要:

def new 
    @campaign = Campaign.new 
    @campaign.messages.build 
end