【问题标题】:Rails - Polymorphic has_many :through associations - 'Can't find source association in model' errorRails - 多态has_many:通过关联 - “在模型中找不到源关联”错误
【发布时间】: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


    【解决方案1】:

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

    当顾问添加注释时,该注释会保存顾问 ID 和注释本身,但当前没有对从顾问接收注释的用户的引用。如果您将用户 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,它应该为该用户返回一个注释数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2016-03-20
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多