I have campaigns and messages. Campaigns have many messages and messages belongs to campaigns. I setup nested attributes for the models and in my view and i'm trying to create a message associated with the model. Here's the code:
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
and the form:
= 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'
I know it's probably something really simple but I keep getting a mass assignment issue with message. Here's the error:
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: message):
app/controllers/campaigns_controller.rb:18:in `update'
and finally the params that get created from the form:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"(removed)", "campaign"=>{"name"=>"Weekly Poker", "group_id"=>"1", "message"=>{"body"=>"s"}}, "commit"=>"Save Campaign", "id"=>"1"}
Because it's a has_many
association it should be in plural form:
= f.fields_for :messages do |m|
Also, in the controller you will need:
def new
@campaign = Campaign.new
@campaign.messages.build
end