rails_admin更改belongs_to下拉菜单以显示不同字段的选项 [英] rails_admin Change belongs_to Drop-down to Display Options from Different Field

查看:236
本文介绍了rails_admin更改belongs_to下拉菜单以显示不同字段的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rails_admin 0.6.5 Rails 4.1.6 并拥有一个 has_many / belongs_to 分别在卷和问题模型之间的关联设置:

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

和问题模型:

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

rails_admin 界面中,它可以工作,但创建或编辑问题时,卷下拉菜单中填充了文本卷#1 卷#2 卷#3 (每个作为单独的选项)。那些卷号对应于:volume_id ,而不是卷的:number 字段,它与ID和因此对用户感到困惑。

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.

创建或编辑问题时,如何控制在 belongs_to 关联下拉菜单?感谢您提前提供的任何帮助。

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.

推荐答案

Rails管理员会查看您的模型中的某些属性以进行显示。有一个数组RailsAdmin.config.label_methods包含这些属性按照首选项。

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.

默认情况下,它们是[:name,:title]

By default they are [:name, :title]

我喜欢将:display_name添加到列表的前端,以便我可以轻松地覆盖在数据库上具有名称列的任何模型。

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.

为了做到这一点,将以下行添加到 config / initializers / rails_admin.rb

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

config.label_methods.unshift(:display_name)

然后,在你的模型中:

    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

这篇关于rails_admin更改belongs_to下拉菜单以显示不同字段的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆