从按日期排序的多个单独关联中返回记录

时间:2017-01-02 19:52:00

标签: ruby-on-rails activerecord

我将具有某些相关通信的用户存储为关联。

Notes,Emails&记录

我想运行一个查询,收集按日期排序的所有相关注释,电子邮件和录音,以便我可以在页面上显示它们。 我现在分开拉它们并将它们分类为红宝石,但我发现这不是非常有效(我不得不拉出所有记录而不仅仅是20的日期范围)或者说will_paginate会返回)。

有没有办法在SQL中实现它来实现它? (由于电子邮件的具体日期与数据库日期无关,因此稍微复杂一点。)

即。使用数组我可以得到

@history = (@user.emails + @user.recordings + @user.notes)
@history = @history.sort_by {|record| (record.class == Email ? record.email_date : record.created_at)}.reverse!

但是我想尝试在SQL查询中提取它,以便最终得到一个响应,其中相关项列出相应数据字段按行顺序列出的每行一条记录。

1 个答案:

答案 0 :(得分:2)

我建议使用Single Table Inheritance。在您的情况下,有两种方法可以做到这一点。选择哪一个取决于每个通信类型的列数'他们有多少不同。

# user.rb
class User
  has_many :communications
end

您使用列type(字符串)创建通信表。

# communication.rb
class Communication < ActiveRecord::Base
  belongs_to :user
end

现在,让您的通讯模型继承上述通讯:

# note.rb
class Note < Communication
end

# email.rb
class Email < Communication
end

# recording.rb
class Recording < Communication
end

用户模型现在自动了解不同的通信类型,因此您可以执行以下操作:

@current_user.notes.where(...)
@current_user.emails.find_by(...)
@current_user.communications.first

简单(但对某些人来说有点混乱)是将所有三个模型(注释,电子邮件,通信)的所有必要列放在通信表中。

另一种方法是在另一个表中移动细节:

# note.rb (all you need in the communications table is a `note_detail_id`)
class Note < Communication
  has_one :note_detail
end

# note_detail.rb (this table carries all the note specific columns) 
class NoteDetail < ActiveRecord::Base
  belongs_to :note
end

现在终于 - 因为你在一张桌子上有所有记录 - 你可以这样做:

@current_user.communications(order: :created_at)