我如何加入has_many,has_many:through和HABTM?

时间:2015-06-30 16:06:32

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

我希望能够编写单个查询来查找用户创建,查看或接收的所有邮件。

这是我的User类的简化版本:

class User < ActiveRecord::Base
  # user_id
  has_many :messages

  # message_viewer_id
  has_many :message_views, foreign_key: 'message_viewer_id'
  has_many :viewed_messages, through: :message_views

  # user_id
  has_and_belongs_to_many :received_messages,
                          join_table: 'messages_recipients',
                          class_name: 'Message'
end

我使用.where.conditions尝试了以下许多变体,但不断出现PG::UndefinedTable: ERROR: missing FROM-clause entry for table "received_messages"

等错误
User.
  joins(:messages,
        :message_views,
        :received_messages).
  where({messages: {user_id: id},
         message_views: {message_viewer_id: id},
         received_messages: {user_id: id}})

(我可以毫无问题地加入:messages:message_views,但在我介绍:received_messages时查询会中断。(是的,我知道我不应该使用HABTM。))< / p>

实现这一目标的最简单和/或最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

class User < ActiveRecord::Base
   ...
    def all_messages
      Message.where("user_id = ? OR id IN (SELECT message_id FROM message_views WHERE message_viewer_id = ?) OR id IN (SELECT message_id FROM messages_recipients WHERE user_id = ?)", self.id, self.id, self.id)
    end
    ...
end

我建议在邮件user_id上添加索引,在message_views上添加message_viewer_id,在messages_recipients上添加user_id,如果还没有。