ruby-on-rails - 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
我如何才能在通知模型中加入关联?
解决方案
也许您想拥有复合主键?如果是这样,您可以这样做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
推荐阅读
- javascript - Javascript中对象的“形状”一词是什么意思?
- windows - FFmpeg Batch 同时遍历两个不同文件夹中的文件
- python - Python Kafka 模拟 Kafka Consumer 的返回类型
- php - 如何解决此错误“访问 https://api.sandbox.paypal.com/v1/payments/payment 时出现 Http 响应代码 400。”
- ios - UICollectionView 水平分页在旋转后不居中
- java - Java - 异步套接字通道无法连接到远程异步服务器套接字通道
- sql - 找到那些状态和颜色相同的团队
- bash - git 用另一个远程备份一个远程存储库
- c# - 打开文件资源管理器以在 ASP.NET MVC 中导出我的水晶报表
- amazon-web-services - 如何在 Terraform 的动态块中使用 for_each 和迭代器?