Rails 2键关联
Rails associate by 2 keys
我有2个模型:通知,邮件。在通知中,在通知中,我有列 object_id 和 notification_type。在 object_id 中写入来自邮件的 ID,在 notification_type - "mail" 中。将来我想将其他模型名称添加到通知中,并与其关联,所以我需要通过 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" = AND "mail...
^
: SELECT "mails".* FROM "mails" WHERE "mails"."id" = AND "mails"."notification_type" = LIMIT
我如何才能加入通知模型?
也许您想要复合主键?如果是这样,你可以这样做 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
我有2个模型:通知,邮件。在通知中,在通知中,我有列 object_id 和 notification_type。在 object_id 中写入来自邮件的 ID,在 notification_type - "mail" 中。将来我想将其他模型名称添加到通知中,并与其关联,所以我需要通过 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" = AND "mail...
^
: SELECT "mails".* FROM "mails" WHERE "mails"."id" = AND "mails"."notification_type" = LIMIT
我如何才能加入通知模型?
也许您想要复合主键?如果是这样,你可以这样做 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