Ruby-on-rails 简单表单关联自定义标签名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6334582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple form association custom label name
提问by dj_44
I have been struggling with what I perceive to be a simple problem:
我一直在努力解决我认为是一个简单的问题:
Working in Rails 3.0.8 with the simple_form 1.4 gem.
使用 simple_form 1.4 gem 在 Rails 3.0.8 中工作。
I have two models, owners and owner_types;
我有两个模型,所有者和所有者类型;
class Owner < ActiveRecord::Base
belongs_to :own_type
attr_accessible :name, :own_type_id
end
class OwnerType < ActiveRecord::Base
has_many :owners
attr_accessible :name, :subtype_name
end
In my the _form partial of the Owner view, I want to have a select box that displays both the name and subtype_name of the owner_type association.
....something like this: Owner Type: [name | subtype_name] eg. [Government | Federal]; [Government | Municipal]
在 Owner 视图的 _form 部分中,我想要一个选择框,显示 owner_type 关联的 name 和 subtype_name。
....像这样:所有者类型:[姓名| subtype_name] 例如。[政府| 联邦]; [政府| 市政]
My view now contains: app/views/owners/_form.html.erb
我的视图现在包含:app/views/owners/_form.html.erb
<%= simple_form_for @owner do |f| %>
<%= f.error_messages %>
<%= f.input :name %>
<%= f.association :owner_type, :include_blank => false %>
<%= f.button :submit %>
<% end %>
...the f.association only list the owner_type.name field by default. How do you specify different fields, or in my case two fields?
...默认情况下,f.association 仅列出 owner_type.name 字段。您如何指定不同的字段,或者在我的情况下指定两个字段?
All help is appreciated; thanks in advance.
感谢所有帮助;提前致谢。
DJ
DJ
回答by Dogbert
You'll have to use the :label_method option for this.
为此,您必须使用 :label_method 选项。
<%= f.association :owner_type, :include_blank => false, :label_method => lambda { |owner| "#{owner.name} | #{owner.subtype_name}" } %>
or, if you define a select_label method on the owner's class, you can do
或者,如果您在所有者的类上定义 select_label 方法,则可以执行
<%= f.association :owner_type, :include_blank => false, :label_method => :select_label %>
回答by rafaelfranca
The easiest way to do this is implement an method to_label on your Model. Like this:
最简单的方法是在你的模型上实现一个 to_label 方法。像这样:
class OwnerType < ActiveRecord::Base
def to_label
"#{name} | #{subtype_name}"
end
end
SimpleForm by default will search fot this methods on your model and use it as label_method, in this order:
默认情况下,SimpleForm 将在您的模型上搜索此方法并将其用作 label_method,按以下顺序:
:to_label, :name, :title, :to_s
You can also change this option on your simple_form.rb initializer, or you can pass a block or a method to :label_methodoption of your input.
您还可以在 simple_form.rb 初始值设定项上更改此选项,或者您可以将块或方法传递给:label_method您的输入选项。

