使用活动记录来实现此sql的更好方法吗?

时间:2019-06-24 03:53:24

标签: sql ruby-on-rails activerecord

select t1.id, t1.title from posts t1
inner join (select title, body from posts group by title) as t2 on t1.title = t2.title where title = ?

尝试过:

Post
  .select(:id, :title)
  .joins('INNER JOIN (SELECT title, body from posts AS t2)')
  .group(:title)
  .where('title = ?', title)

不知道如何将t1设置为它。

否则,也许ActiveRecord::Base.connection是唯一的方法。

更多详细信息

对于此sql:

p = Post.select("t1.title")
        .from("posts t1")
        .joins("INNER JOIN (SELECT title, MAX(id) AS maxID FROM posts WHERE category_id = ? GROUP GY title) AS t2 ON t1.title = t2.title AND t1.id = t2.maxID", 1)

为什么不能在这里的category_id方法中设置参数joins

运行此源代码后,p.title得到了NoMethodError: undefined method title

1 个答案:

答案 0 :(得分:1)

改为使用ActiveRecord::Base.connection.execute