-
Notifications
You must be signed in to change notification settings - Fork 1
18 Assigning Categories to Posts
We don't want to be stuck picking categories from the console forever. Let's add a category dropdown to our post forms. We'll use the collection_select method from ActionView::Helpers::FormOptionsHelper.
We'll call collection_select like this:
f.collection_select :category_id, Category.all, :id, :name, prompt: 'Select a category'To explain the arguments passed to collection_select:
- the attribute to be set (
:category_id) - an array of objects (
Category.all) to used as choices - the method to call on each object to set the
valueof each<option>(we callidon each category to use as the option value) - the method to call on each object to set the text of each
<option>(we callnameon each category) - the options hash (we are setting the
:promptoption, whose value will be used as the placeholder<option>)
_app/views/posts/form.html.erb
<fieldset>
<%= f.label :category_id %><br />
<%= f.collection_select :category_id, Category.all, :id, :name, prompt: 'Select a category' %>
</fieldset>We're not quite done, are we? Do you remember what we need to change in PostController?
We need to permit category_id for mass assignment!
app/controllers/posts_controller.rb
def post_params
params.require(:post).permit(:title, :link, :body, :post_type, :category_id)
endThat allows categories to be assigned when creating or updating posts. Since we have permitted some attributes and not others, failing to permit this new attribute would not normally raise an exception. If you'd like it to raise an exception, add the following to your environment config file:
config/environments/development.rb
config.action_controller.action_on_unpermitted_parameters = :raiseDoes it work? Commit it!
$ git add .
$ git commit -m "Select a category when creating or updating posts."