Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Simple Form custom association select field

I have a select field and I want to put a custom attribute at it called name, I tried to do it like that:

 <%= f.association  :in_charge, :collection => User.lawyer.map{ |l| [l.name, l.id, {:name => l.name.downcase}] } %>    

It works and generates the extra attribute but there is a problem, the select value attribute get changed to the model name attribute, in this case l.name. I changed places and put l.id first but the id attribute is displayed, they get duplicated, any idea why that happens?

Is there another way to define custom attributes at associations select fields?

like image 769
Jirico Avatar asked Jun 11 '12 03:06

Jirico


1 Answers

Use the Rails select() form helper, wrapped by a SimpleForm input.

 <%= f.input :in_charge do %>
   <%= f.select :county_id, User.lawyer.map{ |l| [l.name, l.id, {:name => l.name.downcase}] } %>
 <% end %>

Your code doesn't work as expected because, under the hood, SimpleForm calls collection_select() which doesn't support extra attributes in the option tags.

The SimpleForm readme has the solution as well. But I didn't notice that until I had solved the problem myself :)

like image 185
Will Koehler Avatar answered Nov 10 '22 07:11

Will Koehler