2010-10-20 72 views
2

我將使用通用博客示例。Rails 3查詢界面:使用關聯模型

class Post < ActiveRecord::Base 
    has_many :comments 
end 
class Comment < ActiveRecord::Base 
    belongs_to :post 
end 

查詢Post時,如何訪問其關聯(即:註釋)?

這應該是世界上最簡單的東西,但我還沒有找到任何文檔。即使是http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interfacehttp://m.onkey.org/2010/1/22/active-record-query-interface也無濟於事,基本上說「現在有像連接這樣的方法,並且包含像SQL語句一樣的功能。」是的,謝謝。

因此,這裏有非常簡單的事情,我想做的事情,不工作,但應該是顯而易見的就是我試圖完成:

Post.where(:comments.count >= 10) 
Post.where(:comments.author_id == current_user.id) 
Post.order(:comments.count) 

,我們怎樣才能做到這些不訴諸紅寶石代碼SQL的泄漏(從而破壞了Active Record的目的)? 謝謝:)

+0

Post.includes(「comments」)。where(:comments => {:author_id => current_user.id})似乎適用於第二個,儘管必須使用更少的SQLish/Railsish方法(即類似我在我的問題中所寫的方式)。由於類中的「has_many」方法調用,ARel不應要求我們在查詢中使用SQLish「include」方法。至少應該這樣聰明。 – Arcolye 2010-10-20 10:25:45

+0

很有趣,從2年半前看到我的問題。現在這很簡單。 – Arcolye 2013-05-22 16:30:23

回答

0

如果您在Post上設置了counter_cache作爲評論,您可以直接看到它有多少評論而無需查詢,這使得它更容易和更快。

這將照顧你提出的第一個和最後一個問題。

然後,您可以查詢他們這個樣子,

Post.where(:comments_count >= 10) 
    Post.order(:comments_count) 

但是你最好設置爲範圍。

我不確定你想要做什麼第二個問題,你想顯示當前用戶評論過的所有帖子?

+0

至於你最後的問題,是的,這是正確的。 – Arcolye 2010-10-22 09:28:25

-1

Post.where(:comments.count> = 10)

Post.find(:all).select{|p| p.comments.count >= 10) 

Post.where(:comments.author_id == current_user.id)

Post.find(:all).select{|p| p.comments.select{|c| c.author_id == current_user.id } } 

郵.order(:comments.count)

Yikes, this one beats me. 

嘿,還有,我的兩個帖子在SQL上有點沉重。我知道人們做得更精緻與

Post.find(:all, :conditions => blah blah blah.. 

但我不知道如何把這一點。抱歉。