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'

最后是从表单创建的参数:

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

1 回答 1

0

因为它是一个has_many关联,所以它应该是复数形式:

= f.fields_for :messages do |m|

此外,在控制器中,您将需要:

def new
  @campaign = Campaign.new
  @campaign.messages.build
end
于 2012-11-07T17:10:15.183 回答