【问题标题】:Ruby on Rails two separate polymorphic associations between two tablesRuby on Rails 两个表之间的两个独立的多态关联
【发布时间】:2016-03-27 19:11:33
【问题描述】:

我已经被这个问题困扰了几天,我发现了一些其他类似的堆栈问题,但解决方案没有帮助。我正在尝试在两个表之间创建两个单独的多态关联。我有一个用户表、一个业务表和一个消息表。我不希望用户能够通过一对一的对话互相发送消息。

这是我的消息架构:

class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
       t.references :receiver, polymorphic: true, index: true
       t.text :message
       t.boolean :status, default: false
       t.references :sender, polymorphic: true, index: true
       t.timestamps
     end
  end
end

消息模型

class Message < ActiveRecord::Base
   belongs_to :sender, polymorphic: true
   belongs_to :receiver, polymorphic: true

   scope :unread, lambda {|| where("status = false")}

end

用户模型

    has_many :messages, as: :sender
    has_many :messages_out, as: :receiver, source: :messages

商业模式

    has_many :messages, as: :sender
    has_many :messages_out, as: :receiver, source: :messages

Rails 控制台

2.2.1 :060 > User.first.messages_out
User Load (1.3ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1
NameError: uninitialized constant User::MessagesOut

当我尝试以发件人身份访问消息时,它工作得很好,并且我得到了预期的输出。我尝试将第一个关系的名称更改为其他名称,但是这两个关系都会失败。

User.first.messages

我尝试了几种变体,但似乎都不起作用.

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-4


    【解决方案1】:

    您需要明确说明messages_out 方法应该加载哪个类:

    has_many :messages_out, as: :receiver, source: :messages, class_name: "Message"
    

    【讨论】:

    • 是的,我之前尝试过类似的方法,但它仍然给了我一个错误。 NameError: 未初始化的常量 User::MessagesOut
    • 将上述行添加到用户和业务之后?不知道还有什么可能导致它
    • 哇,它看起来现在可以工作了,我关闭了我的终端并重新打开它,它开始使用你给我的解决方案。真的很奇怪我正在重新加载!我会尽快接受你的回答。谢谢!看起来我什至不需要源标签。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多