Rails Simple Form custom association select field

本小妞迷上赌 提交于 2019-12-28 05:44:05

问题


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?


回答1:


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 :)




回答2:


For the records, it seems that this is working now:

f.association :product, collection: Product.all.map { |product| [product.name, product.id, {data: {description: product.description}}] }

SimpleForm version:

$ bundle show simple_form
/Users/josh/.rvm/gems/ruby-2.4.1@a4aa2/gems/simple_form-4.1.0


来源:https://stackoverflow.com/questions/10974304/rails-simple-form-custom-association-select-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!