Rails简单的自定义关联选择字段

时间:2022-11-23 10:18:40

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

我有一个select字段,我想在它上面添加一个自定义属性name,我试着这样做:

 <%= 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?

它可以工作并生成额外的属性,但是有一个问题,select value属性被更改为model name属性,在这里是l.name。我换了位置,写了l。首先,id属性被显示出来,它们被复制,知道为什么会这样吗?

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

是否有其他方法在关联选择字段中定义自定义属性?

1 个解决方案

#1


24  

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

使用由SimpleForm输入包装的Rails select()表单帮助程序。

 <%= 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.

您的代码不能正常工作,因为在引擎盖下,SimpleForm调用collection_select(),它不支持选项标签中的额外属性。

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

SimpleForm readme也有解决方案。但直到我自己解决了这个问题,我才注意到

#1


24  

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

使用由SimpleForm输入包装的Rails select()表单帮助程序。

 <%= 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.

您的代码不能正常工作,因为在引擎盖下,SimpleForm调用collection_select(),它不支持选项标签中的额外属性。

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

SimpleForm readme也有解决方案。但直到我自己解决了这个问题,我才注意到