I have two models, Story and Category. Using the form for Story#new, I’d like to be able to save the foreign key for Category.
To display the selection data from Category on the Story#new form page I’ve used:
<%= collection_select(:category , :category, Category.all , :id, :category, {:prompt => 'Select Category...'}) %>
How can I save category_id to the newly created Story object?
Story has attributes: industry_id and user_id, Category has attribute name
development.log tells me this: (it looks like it’s trying to add a new category (99) to the Categories table
Started POST "/stories" for 127.0.0.1 at 2012-02-10 17:32:56 -0600
Processing by StoriesController#create as HTML
story"=>{"industry_id"=>"8", "user_id"=>"8"}, "category"=>{"category"=>"99"}, "commit"=>"Create Story"}
I think you need to change the parameters to
collection_select. The first parameter is the name of the model. The second parameter is the name of the model attribute that the value will be assigned to. The fourth parameter is the method of theCategoryobject to use as the text value of the select option.I believe it should look like this:
You might also want to look at ActiveRecord nested attributes.