2012-11-07 61 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