2012-02-29 102 views
0
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) 

如何加入cp成为post_id列的表状结构?如何使用select_all结果按列添加ActiveRecord结果?

就像在SQL:

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

非常感谢。

回答

0

此代码,如你所愿

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

会生成SQL。您可以访问的内容分别为每个岗位在each周期或产生平面表像DB返回执行这样的事情:

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

NoMethodError:未定义的方法'合并”为#<学校:...>,任何想法?谢谢。 – 2012-02-29 14:36:27

+0

哦,对不起,我的错误。这不起作用,因为它不是哈希,它是对象。你可以玩,并用'{:post_id => c.post.id,:content_name => c.name,:post_name => c.post.name}替换'c.merge(c.post)''或任何你喜欢的。这里更重要的是Rails已经拥有了来自数据库的所有必要数据,您可以随意使用它们。 – RaskolnikOFF 2012-02-29 14:47:01

+0

对不起,我只是不熟悉它。我用'{:post_id => c.post.id}'替换了'c.merge(c.post)''。但':post_id'是未定义的。仍在试图弄清楚... – 2012-02-29 16:36:28