2012-02-29 6 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) 

参加方法cppost_idカラムで表のようになりますか?ちょうどSQLのようActiveRecordの結果をselect_allの結果と列で結合する方法はありますか?

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:、任意のアイデアを:未定義のメソッド '#<...学校>​​は「マージ?ありがとう。 –

+0

ああ、申し訳ありませんが、私の間違い。ハッシュではないので、これは機能しません。オブジェクトです。たとえば 'c:post.id、>:c.post.id、:content_name => c.name、:post_name => c.post.name}'と置き換えることができます。またはあなたが好きなものを。ここで重要なのは、RailsにはすでにDBから必要なデータがすべてあり、好きなように使用できるということです。 – RaskolnikOFF

+0

申し訳ありませんが、私はそれに精通していません。私は 'c.merge(c.post)'を '{:post_id => c.post.id}'に置き換えました。しかし ':post_id'は未定義です。まだそれを理解しようとしている... –