【问题标题】:Rails associate by 2 keysRails 通过 2 个键关联
【发布时间】: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


【解决方案1】:

也许您想拥有复合主键?如果是这样,您可以这样做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

【讨论】:

    猜你喜欢
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多