【问题标题】:How to concatenate two ActiveRecord queries in Rails如何在 Rails 中连接两个 ActiveRecord 查询
【发布时间】:2013-03-17 03:51:44
【问题描述】:

我有一个简单的应用程序,其中包含用户模型、角色模型、带有收件人的消息模型。 一个用户通过角色有很多消息 并且一个角色有很多通过收件人的消息,而一个用户也有很多通过收件人的消息。

收件人模型有一个 user_id、role_id 和 message_id

现在我想在一个查询中显示用户的所有消息,包括他的角色消息和他的个人消息。我怎样才能做到这一点。

 role model

 has_many :recipients
 has_many :received_messages, :class_name => 'Message', :order => 'created_at desc', through: :recipients

 user model
 has_many :roles
 has_many :received_messages, :class_name => 'Message', :order => 'created_at desc', through: :roles, :uniq => true
 has_many :recipients
 has_many :private_messages, :class_name => 'Message', :order => 'created_at desc', through: :recipients

 message model
 has_many :recipients
 has_many :roles, :through => :recipients
 has_many :users, :through => :recipients

有了所有这些,我将如何获取用户消息,包括他的角色消息和他的私人消息

例子

def all_messages
  @all_messages = current_user.#all messages scope here#
end

【问题讨论】:

  • 你有 has_many :roles 用于用户模型。这意味着您在角色模型上有一个 belongs_to :user 对吗?

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


【解决方案1】:

获取所有消息的一种方法是在 all_messages 方法中将 received_messages 数组与 private_messages 数组结合起来。这将返回一个包含所有用户消息的数组。

def all_messages
  (current_user.received_messages + current_user.private_messages).uniq
end

【讨论】:

  • 不错。谢谢,我从来没有接触过 concat 方法
  • 我试过了,我得到了以下错误Cannot modify association 'User#received_messages' because it goes through more than one other association.
  • 射击,我忽略了这一点。是的,这是有道理的,它不会让您修改通过 ActiveRecord 关联创建的数组。我刚刚为你更新了我的答案。
  • 它会多次复制消息
  • 我之前添加了 + 号,但我很害怕。我认为这是一种不好的做法。是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
相关资源
最近更新 更多