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

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

问题描述

我有一个选择字段,我想在它上面放置一个名为 name 的自定义属性,我尝试这样做:

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}] } %>    

它可以工作并生成额外的属性,但有一个问题,选择值属性更改为模型名称属性,在本例中为 l.name.我更改了位置并将 l.id 放在首位,但显示了 id 属性,它们会重复,知道为什么会发生这种情况吗?

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?

推荐答案

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

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

您的代码没有按预期工作,因为在底层,SimpleForm 调用了 collection_select() 不支持选项标签中的额外属性.

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 自述文件也包含解决方案.但是直到我自己解决了这个问题我才注意到:)

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天全站免登陆