【发布时间】:2020-02-04 07:37:16
【问题描述】:
我有 2 个模型:通知、邮件。在通知中 在通知中我有列 object_id 和 notification_type。在 object_id 中写入来自邮件的 id,在 notification_type -“邮件”中。将来我想将其他模型名称添加到通知中,并与其关联,所以我需要通过 id 和类型模型进行关联。现在我有了关联:
class Mail < ApplicationRecord
has_many :notification, -> {where(notification_type: "mail") }, class_name: "Notification", foreign_key: "object_id"
end
它的工作,但我现在不知道如何在通知中关联,将在哪里采用通知类型。我试试
class Notification < ApplicationRecord
belongs_to :mail, class_name: "Mail", foreign_key: "object_id"
end
在这种情况下,notification_type 不考虑关联。
class Notification < ApplicationRecord
belongs_to :mail, -> {where(notification_type: "mail") }, class_name: "Mail", foreign_key: "object_id"
end
我得到错误
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column mails.notification_type does not exist)
LINE 1: ...ils" WHERE "mails"."id" = $1 AND "mail...
^
: SELECT "mails".* FROM "mails" WHERE "mails"."id" = $1 AND "mails"."notification_type" = $2 LIMIT $3
我如何才能在通知模型中加入关联?
【问题讨论】:
-
在我看来,你正在构建一些已经存在于 Rails 中的东西。您是否可能想要polymorphic association?
-
谢谢。现在使用多态关联)
标签: ruby-on-rails ruby associations