Reputation: 67
I have collection_select
in one of my views, which properly creates a HTML <select>
menu, but when I select an option it does not save in the database. In the same view I have other fields from the same db table and they save up. Here are my models:
class TrainingPart < ActiveRecord::Base
belongs_to :activity
belongs_to :training
accepts_nested_attributes_for :activity, :allow_destroy => true
end
class Activity < ActiveRecord::Base
has_many :training_parts
end
The partial is:
<div class="part">
<%= f.label :activity, "Activity" %>
<%= collection_select :training_part, :activity_id, Activity.all, :id, :name %>
<%= f.text_field :activity_id %>
<%= f.text_field :amount %>
</div>
The amount
field works fine.
EDIT: I don't use attr_accessible
in any model, so all of the fields in all tables are accessible. (reference: Rails mass assignment definition and attr_accessible use)
Upvotes: 1
Views: 2954
Reputation: 59509
For me the problem was that I didn't whitelist the field in my controller.
Say your select menu has blog posts as options so you can choose what blog a comment belongs to
f.collection_select :post_id, Post.all, :id, :name
Then you'll need to permit post_id
in your CommentsController
def update
# ...
if @comment.update_attributes(post_params)
# ...
end
def post_params
params.require(:comment).permit(:name, :post_id) # Make sure the field used with your select menu is permitted!
end
Upvotes: 0
Reputation: 67
I managed to do it. It turned out that I had 2 mistakes:
1) I had to remove <%= f.text_field :activity_id %>
from the view as this was the field, which I was trying to set with the select menu.
2) I should've used f.collection_select
instead of collection_select
Upvotes: 1
Reputation: 6682
Allow mass-assignment to whatever attributes you want settable from the view:
attr_accessible :activity_id, :amount # ...any others...
"Mass-assignment" means setting many attributes at once with data from the view, such as from forms. These attributes are protected by default to prevent users from injecting their own values (eg. admin = true
).
Use attr_accessible
to declare which of your model's attributes are mass-assignable.
Also, since you are accepting nested attributes for Activity
, you must include :activity_attributes
among your list of accessible attributes.
Upvotes: 0