【发布时间】:2017-01-07 16:19:58
【问题描述】:
我一直在网上搜索并尝试了很多不同的方法来解决这个问题,但我真的被困住了。我对 Rails 很陌生,所以我可能错过了一些明显的东西!
我遇到的问题是涉及 4 个模型的多态关联:
(1) 用户,(2) 批准人,(3) 收件人,(4) 备注
一个用户有很多审批者,也有很多接收者。用户还可以为审批者和收件人留下备注。注释与批准者和接收者具有多态关联,如 :notable。我的模型如下所示:
Note.rb
class Note < ApplicationRecord
belongs_to :user
belongs_to :notable, polymorphic: true
end
Approver.rb
class Approver < ApplicationRecord
belongs_to :user
has_many :notes, as: :notable
end
收件人.rb
class Recipient < ApplicationRecord
belongs_to :user
has_many :notes, as: :notable
end
用户.rb
class User < ApplicationRecord
has_many :approvers, dependent: :destroy
has_many :recipients, dependent: :destroy
# This is the bit that I think is the problem:
has_many :notes, through: :approvers, source: :notable, source_type: "Note"
has_many :notes, through: :recipients, source: :notable, source_type: "Note"
end
基本上我希望能够做到
User.find(1).notes (...etc)
并显示来自批准者和收件人的该用户的所有注释。
例如,在审批者视图中,我可以执行 @approver.notes.each 并很好地遍历它们。
我收到的错误消息是:“在模型收件人中找不到源关联 :note_owner。尝试 'has_many :notes, :through => :recipients, :source => '。是一个用户或笔记?”
谁能看到我错过了什么!?
【问题讨论】:
标签: ruby-on-rails ruby associations has-many-through polymorphic-associations