Operation of the helper collection_select

Asked

Viewed 138 times

0

Good morning, I’m a beginner in Rails and would like to know how the helper collection_select of Rails works, I could not deduce based on explanations and examples in the official documentation.

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)

1 answer

1


Hello, it basically works as follows, I took from the official documentation too https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_select

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)

:post => Name of your select, usually the class of your model as well

:author_id => Your model field (in the data table, which the Post is bound belongs_to :author), what will generate the field name for example: post[author_id]

Author.all => It’s the list of all the authors in the database, the method. all of a class inherited by Activerecord, go to the bank and search all the values of this table

:id => You will take the field ID to fill in the value of the select, which is the value that will go to the controller when you submit the form

:name_with_initial => It is taking in the Author model this class, which is the first name name + the second name, is the one that will appear in select field’s home option

:prompt: true => It will have an "empty" option in select, that’s good, because if it doesn’t, it will see the first value found with Author.all and the person can select "anything" and not even realize that this field was filled with the wrong value

  • See if my thinking is correct, the :post is representing the instance that will receive the value of :id in the field :author_id, that :id is a property of the Author template. In HTML each option own the property value with a value of :id of each value in the Authors table and the function name_with_initial returns the first letter of the property first_name and the value of the property last_name as output of each option in the select.

  • If what I said is correct still left me doubt, what the need of value post[author_id] on the property name of select in this example, he is doing something?

  • the params that go to the backend are named by the "name" of the select, in which case.

  • in your controller in the case, will come a hash + or so { post: { author_id: 1 } } drew?

  • I understood yes, obg for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.