Skip to content

18 Assigning Categories to Posts

Dave Strus edited this page May 6, 2015 · 1 revision

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 value of each <option> (we call id on each category to use as the option value)
  • the method to call on each object to set the text of each <option> (we call name on each category)
  • the options hash (we are setting the :prompt option, 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)
  end

That 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 = :raise

Does it work? Commit it!

$ git add .
$ git commit -m "Select a category when creating or updating posts."

Clone this wiki locally