首页 > 解决方案 > Rails 通过 2 个键关联

问题描述

我有 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

我如何才能在通知模型中加入关联?

标签: ruby-on-railsrubyassociations

解决方案


也许您想拥有复合主键?如果是这样,您可以这样做https://github.com/composite-primary-keys/composite_primary_keys

class Membership < ActiveRecord::Base
  self.primary_keys = :user_id, :group_id
  belongs_to :user
  belongs_to :group
  has_many :statuses, :class_name => 'MembershipStatus', :foreign_key => [:user_id, :group_id]
end

与复合键模型关联的模型定义如下:

class MembershipStatus < ActiveRecord::Base
  belongs_to :membership, :foreign_key => [:user_id, :group_id]
end

推荐阅读