如何通过列加入select_all结果的ActiveRecord结果?

时间:2012-02-29 13:47:55

标签: ruby-on-rails ruby activerecord

class Author
  has_many :post
end

class Post
  belong_to :author
  has_many :content
end

class Content
  belong_to :post 
  (column: section)
end



c = Content.select("post_id").where("section like ?", 'foo%')
p =  ActiveRecord::Base.connection.select_all(Post.select("title, post_id ").joins(:author).where(:id => c.map(&:post_id)).to_sql)

如何通过c列加入ppost_id成为类似于表格的结构?

就像在SQL中一样:

  select * from c,p where c.post_id = q.post_id ; 

非常感谢。

1 个答案:

答案 0 :(得分:0)

此代码

@posts = Content.find(:all, :include => :post)

将根据需要生成SQL。您可以在each周期中单独访问每个帖子的内容,或生成平面表,如DB返回执行以下操作:

@posts = Content.find(:all, :include => :post).map{|c| c.merge(c.post)}