Rails collection_select parameters
Collection_select is a method in Rails that enables you to turn collections into a set of option tags in your HTML page.
This method is usually used to associate models. We could use it for example, we have an owner and pet models. When we create a new pet, you want to be able to select an owner for that pet, we can use collection_select for this.
We should have our models created.
class Pet< ActiveRecord::Base
belongs_to :owner
endclass Owner< ActiveRecord::Base
has_many :pets
end
We can use collection_select for forms, lets look at the documentation before do anything.
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
Well now that we know what we will be using let’s start by creating a form.
<%= form_for(@pet) do |f|%><%= f.label :name %><%= f.text_field :name %><br>
<%= f.label :age %><%= f.text_field :age %><br>
<%= f.submit %><% end %>
Well now we have a form that takes 2 inputs a name and age of a pet. Now let’s start doing the Collection_select.
1- Lest give a label to the selection.
<%= f.label :age %>
2- Then we start the collection_select and give the method of the selection, in this case owner_id
<%= f.label :age %>
<%= f.collection_select :owner_id%>
3- Then we give the collection which in this case will be an array of Owners
<%= f.label :age %>
<%= f.collection_select :user_id, User.all%>
4- The next method we must add is the value_method, in this case will be the id of the owner.
<%= f.label :age %>
<%= f.collection_select :user_id, User.all, :id%>
5- The last method we need is text_method which is what the use will see in the drop-down menu, in our case it will be the name of the owner.
<%= f.label :age %>
<%= f.collection_select :user_id, User.all, :id, :name%>
The first time I used collection_select I was so confused, I hope this step by step guide will help someone to understand a bit more this method that you will be using a lot in your code.