1

我一直在搜索互联网,并尝试了很多不同的方法来解决这个问题,但我真的被卡住了。我相当新的轨道,所以我可能错过了明显的东西!Rails - 多态has_many:通过关联 - '找不到模型中的源关联'错误

我的问题是与涉及4个车型多态关联:

(1)用户,(2)审批,(3)收件人,(4)注意

用户具有许多批准者,并具有许多收件人。用户还可以为审批者和收件人留下备注。注释与审批者和收件人之间具有多态关联:值得注意。我的模型如下所示:

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 

Recipient.rb

class Recipient < ApplicationRecord 
    belongs_to :user 
    has_many :notes, as: :notable 
end 

User.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 =>'。用户或笔记之一?“

任何人都可以看到我失踪!?

回答

0

为了按照您提到的方式获取用户笔记,您必须为该用户添加一个外键。例如,

当顾问添加注释时,该注释将保存顾问ID和注释本身,但目前没有提及从顾问那里接收注释的用户。如果添加到用户标识引用的笔记架构,则可以提取特定用户的所有笔记。

EX。

注架构:

user_id: references (the user the note is for) 
writer_id: references (the user that writes the note) 
note: text (your actual note) 

可以比建立一个音符,就象这样:

current_user.create_note(params[:user], params[:note]) # pass the user as a reference 

def create_note(user, note) 
    Note.create(user_id: user.id, 
       write_id: current_user.id 
       note: note) 
end 

一旦创建这样的用户,你可以在任何用户拨打:user.notes它应该返回该用户的一系列注释。

相关问题