rails_admin Change belongs_to Drop-down to Display Options from Different Field

点点圈 提交于 2019-12-24 02:07:39

问题


I am using rails_admin 0.6.5 with Rails 4.1.6 and have a has_many / belongs_to association setup between the Volume and Issue models respectively:

class Volume < ActiveRecord::Base
  has_many :issues, :inverse_of => :volume

  validates :number, presence: true, numericality: {greater_than_or_equal_to: 1}
end

and the Issue model:

class Issue < ActiveRecord::Base
  belongs_to :volume, :inverse_of => :issues

  validates :number, presence: true, numericality: {greater_than_or_equal_to: 1}
  validates :date, presence: true
end

Within the rails_admin interface, it works but when creating or editing an Issue, the Volume drop-down menu is populated with the text Volume #1, Volume #2, Volume #3 (each as a separate option). Those "volume numbers" correspond to :volume_id, not the Volume's :number field, which is different than the ID and therefore confusing to users.

When creating or editing an Issue, how do I control which Volume column is displayed in the belongs_to association drop-down menu? Thank you in advance for any help provided.


回答1:


Rails Admin looks for certain properties on your model for display purposes. There is an array RailsAdmin.config.label_methods that contains these properties in order of preference.

By default they are [:name, :title]

I like to add :display_name to the front of the list so that I can easily override any models that have a name column on the db.

In order to do this, add the following line to config/initializers/rails_admin.rb

config.label_methods.unshift(:display_name)

Then, in your model:

    class Volume < ActiveRecord::Base

      has_many :issues, :inverse_of => :volume

      validates :number, presence: true, numericality: {greater_than_or_equal_to: 1}

      def display_name
        "Volume #{self.number}"
      end

    end


来源:https://stackoverflow.com/questions/26590997/rails-admin-change-belongs-to-drop-down-to-display-options-from-different-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!