Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

ruby on rails - Simple form association custom label name

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.

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]

My view now contains: 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?

All help is appreciated; thanks in advance.

DJ

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll have to use the :label_method option for this.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...