Simple form association custom label name

前端 未结 2 560
臣服心动
臣服心动 2020-12-23 20:06

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_

相关标签:
2条回答
  • 2020-12-23 20:46

    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 %>
    
    0 讨论(0)
  • 2020-12-23 21:02

    The easiest way to do this is implement an method to_label on your Model. Like this:

    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:

    :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_method option of your input.

    0 讨论(0)
提交回复
热议问题