简单表单关联自定义标签名称

时间:2011-06-13 18:28:45

标签: ruby-on-rails simple-form

我一直在努力解决我认为是一个简单的问题:

使用simple_form 1.4 gem在Rails 3.0.8中工作。

我有两个模型,所有者和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

在我所有者视图的_form部分中,我希望有一个显示owner_type关联的名称和子类型名称的选择框。
   ....像这样:所有者类型:[名字| subtype_name]例如。 [政府|联邦]; [政府|市政]

我的观点现在包含: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 %>

... f.association默认只列出owner_type.name字段。你如何指定不同的字段,或者在我的情况下指定两个字段?

感谢所有帮助;提前谢谢。

DJ

2 个答案:

答案 0 :(得分:82)

您必须使用:label_method选项。

<%= f.association :owner_type, :include_blank => false, :label_method => lambda { |owner| "#{owner.name} | #{owner.subtype_name}" } %>

或者,如果在所有者的类上定义select_label方法,则可以执行

<%= f.association :owner_type, :include_blank => false, :label_method => :select_label %>

答案 1 :(得分:50)

最简单的方法是在模型上实现to_label方法。像这样:

class OwnerType < ActiveRecord::Base
  def to_label
    "#{name} | #{subtype_name}"
  end
end

默认情况下,SimpleForm将在您的模型上搜索此方法并将其用作label_method,按此顺序:

:to_label, :name, :title, :to_s

您也可以在simple_form.rb初始值设定项中更改此选项,也可以将块或方法传递给输入的:label_method选项。

相关问题