Rails collection_select vs f.collection_select

form-for, forms, ruby-on-rails

Solution

When you use `f.some_form_helper` the helper will already know the name of the model you want to make the field name for. This way you can drop that `:post` argument. `form_for(@post)` gives you the `f` form builder object that knows what model the form is for.

With the regular `collection_select` (or any other helper with `f.`) you have to pass in, as the first argument, the name of the model the field is for.

Your example is a bit off because you passed in the same arguments to both. `f.collection_select` doesn't need the `:post`.

This is correct use of the non `f.` helper:

<%= collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true) %>

This is a corrected way to use the `f.` helper:

<%= f.collection_select(:author_id, Author.all, :id, :name_with_initial, prompt: true) %>

the `f` object has a reference back to the model you passed in to `form_for` via `f.object`. This is how it knows to call `collection_select(:post, ...)` under the hood.

Problem

I can't understand the difference between the two. Can someone please explain the difference when using form_for? Say you have this: `<%= form_for(@post) do |f| %>` Examples- When would you use this? `<%= collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true) %>` vs. use this? `<%= f.collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true) %>` Rails Api

Original source