rails admin 上的多态关联未正确显示

Polymorphic association not showing correctly on rails admin

我刚刚在我的应用程序中添加了一些通知功能。但是,当我检查 rails admin 上的通知时,它没有检测到关联的多态对象。 我只在开发中使用 rails admin.. 所以如果这是一个 rails admin 错误,那么我很乐意离开它。但是(而且很可能)如果我做错了什么,我需要修复它。

我应该提一下 - 这在数据库中工作并且在站点的任何地方都有效,除了 rails admin

我的模型

class Notification < ActiveRecord::Base
  belongs_to :notified, polymorphic: true
  belongs_to :object, polymorphic: true
  belongs_to :user

  scope :not_seen, -> { where(seen: false) }
  scope :not_clicked, -> { where(clicked: false) }


  def self.send_notifications(user, message, object, subscribers, mailer = nil, mailer_object = nil)
    subscribers.uniq.each do |subscriber|
      self.create({user: user, message: message, notified: subscriber, object: object}) unless subscriber.get_user_id == user.id
      UserMailer.send(mailer, subscriber, mailer_object).deliver unless mailer.nil? || subscriber.get_user_id == user.id
    end
  end

end

All_Models_that_can_be_notified_about.rb

class .... < ActiveRecord::Base
..
  has_many :notifications, as: :object
..
end

这是创建通知的行

self.create({user: user, message: message, notified: subscriber, object: object}) unless subscriber.get_user_id == user.id

这是它在控制台上的样子:

<Notification id: 7, user_id: 1, message: " has left a comment on ", notified_id: 2, notified_type: "Programme", created_at: "2015-10-09 12:51:07", updated_at: "2015-10-09 12:51:07", seen: true, clicked: true, object_id: 54, object_type: "Applicant">

正如您从上面看到的,object_idobject_type 填充了 (54, Applicant)

但是在 Rails 管理员中,我得到了这个:

它正在检测模型是申请人,但它没有看到 ID

有什么想法吗?

您似乎发现了 Rails 所遭受的罕见且令人困扰的名称冲突之一。在 Rails Guide to ActiveRecord Associations

中对此进行了非常简短的提及

3.2 Avoiding Name Collisions

You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things. For instance, attributes or connection are bad names for associations.

object_id 由 Ruby 在所有对象上定义。它 returns 标识对象的数字 ID,不幸的是(正如您发现的那样),可以用另一个方法覆盖此方法,这就是当您创建名为 object 的关联时发生的情况。

当从具有名为 object_id 的列的 table 实例化模型时,会自动添加 object_id 属性。在某些时候调用 object_id 方法来识别对象,但返回的值来自属性。因此问题。

重命名协会可能是解决此问题的唯一方法。