我的Rails应用程序正在使用auditor gem来获取两个模型的更改历史记录:
@audit = Audit.where( :auditable_id => current_user.posts,
:auditable_type => "Post") +
Audit.where( :auditable_id => @comments,
:auditable_type => "Comment")
这样可行,但我需要在更改时对整个@audit
变量进行排序。
我有两个问题要解决。
sort
,sort_by
,order
我需要弄清楚我需要按以下哪个字段排序:
=> Audit(id: integer, auditable_id: integer, auditable_type: string, owner_id: integer, owner_type: string, user_id: integer, user_type: string, action: string, audited_changes: text, version: integer, comment: text, **created_at**: datetime)
1.9.3-p194 :002 > Audit.last
Audit Load (168.0ms) SELECT "audits".* FROM "audits" ORDER BY version DESC, created_at DESC LIMIT 1
=> #<Audit id: 5, auditable_id: 58, auditable_type: "Post", owner_id: 58, owner_type: "Post", user_id: 1, user_type: "User", action: "update", audited_changes: {"status"=>["to approve", "to review"], " **updated_at** "=>[2012-08-24 15:29:26 UTC, 2012-08-24 19:29:52 UTC]}, version: 2, comment: "post modified by Bruno Amaral ", created_at : "2012-08-24 19:29:52">
答案 0 :(得分:1)
您应该能够构建单个查询来加载您感兴趣的所有Audit
个对象。由于它是单个查询,因此数据库也可以处理排序。
您要执行的SQL看起来像这样:
SELECT *
FROM audits
WHERE
auditable_type = 'Post' AND auditable_id = … OR
auditable_type = 'Comment' AND auditable_id IN (…)
ORDER BY created_at
你应该能够使用Arel构建这样的东西(假设你正在使用Rails 3):
t = Audit.arel_table
for_post = t[:auditable_type].eq('Post').and(t[:auditable_id].eq(post.id))
for_comments = t[:auditable_type].eq('Comment').and(t[:auditable_id].in(comment_ids))
audits = Audit.where(for_post.or(for_comments)).order(:created_at)
有关使用Arel构建复杂查询的详细信息,请参阅ASCIIcasts episode 215和Arel README。
如果您不喜欢Arel语法,您也可以使用find_by_sql
或pass a string to where
,但请记住,使用Arel可以保护您免受各种错误和数据库之间的细微差别。
答案 1 :(得分:0)
@audit = Audit.where( "auditable_id IN (?) OR auditable_id IN (?)",
current_user.posts,
@comments ).order_by( :created_at )