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 eachoption
own the propertyvalue
with a value of:id
of each value in the Authors table and the functionname_with_initial
returns the first letter of the propertyfirst_name
and the value of the propertylast_name
as output of eachoption
in theselect
.– B. Dias
If what I said is correct still left me doubt, what the need of value
post[author_id]
on the propertyname
ofselect
in this example, he is doing something?– B. Dias
the
params
that go to the backend are named by the "name" of the select, in which case.– Andre Leoni
in your controller in the case, will come a hash + or so
{ post: { author_id: 1 } }
drew?– Andre Leoni
I understood yes, obg for the help!
– B. Dias