rails grouped_collection_select

rails grouped_collection_select

Hey everyone!

I wanted to share some information on the grouped_collection_select method for rails forms. I wanted to create a drop down list from two different models that one has a reference of another. Sadly I couldn't find much documentation and implementation of this method and I think its important as users will run into this when creating dropdown lists.

First let me show you what my two models looks like

class Agent < ApplicationRecord
  belongs_to :company
end
class Company < ApplicationRecord
  has_many :agents
end        

Now each agent had a reference of the company_id in the schema. What our goal is, is to create a dropdown list of companies with the agents nested within each company. This is where grouped_collection_select is used.


<%= f.grouped_collection_select :agent, @companies,:agents,:name,:id, :name%
>        

.Lets break down each option so we can see what is going on.

:agent => The name of the parameter your setting the value to

@companies => Company.all => The name of the parent collection within the relation.

:agents => The name of the children that belong to each company

:name => What is going to be displayed on the dropdown for each company.

:id => The value that you want to submit

:name => The name of the agent

The result of this creates the following html


<select name="listing_agent[agent]" id="listing_agent_agent">
<optgroup label="Company 1">
  <option value="2">Agent 1 of company 1 name</option>
  <option value="3">Agent 2 of company 1 name</option>
</optgroup><optgroup label="Company 2">
  <option value="29">Agent 1 of company 2 name</option>
  <option value="30">Agent 2 of company 2 name</option>
  <option value="31">Agent 3 of company 2 name</option>
...        

I hope this helped anyone that is looking into this issue!

Vicki Anderson Estes

Associate Broker, REALTOR, Today's Realty

1 年

You so smart!??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了