2012-02-29 104 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