Rails简单表单自定义关联选择字段 [英] Rails Simple Form custom association select field

查看:180
本文介绍了Rails简单表单自定义关联选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择字段,我想把一个自定义属性称为名称,我试图这样做:

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

它可以工作并生成额外的属性,但有一个问题,select value属性会更改为型号名称属性,在本例中为l.name。我改变了地方,并首先把l.id,但ID属性显示,他们得到重复,任何想法为什么会发生?

是否有另一种方法来定义自定义属性关联选择字段?

解决方案

使用Rails select()表单助手,由SimpleForm输入封装。

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

您的代码无法按预期工作,因为在此基础上,SimpleForm调用 collection_select(),它不支持选项标签中的额外属性。



SimpleForm自述文件包含解决方案。但是我没有注意到,直到我自己解决了这个问题:)

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?

解决方案

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

这篇关于Rails简单表单自定义关联选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆