2011-04-25 173 views
4
model Post 
    # ActiveRecord associations have tons of options that let 
    # you do just about anything like: 
    has_many :comments 
    has_many :spam_comments, :conditions => ['spammy = ?', true] 

    # In Rails 3, named scopes are ultra-elegant, and let you do things like: 
    scope :with_comments, joins(:comments) 
end 

有沒有什麼方法可以使用AREL或其他更精簡的語法來將自定義關聯定義爲與命名作用域一樣優雅?有沒有辦法使用AREL進行自定義關聯?

更新

我已經決定了這不是一個好主意,把那種細節的爲關聯關係,無論如何,因爲協會應始終/大都定義模型之間的基本關係。

回答

3

解決的辦法之一就是把垃圾範圍點評:

model Post 
    has_many :comments 

    scope :with_comments, joins(:comments) 
end 

model Comment 
    scope :spammy, where(:spammy => true) 
end 

這看起來有點清潔關於模型的責任。性能方面它是完全一樣的:

p.comments.spammy.to_sql 
# → SELECT "comments".* FROM "comments" 
# WHERE ("comments".post_id = 2) AND ("comments"."spammy" = "t") 

額外的好處:你可以從任何其他協會取得垃圾評論。

+0

是的我見過這個......我認爲把它稱爲「關聯」並不好,因爲它沒有定義兩個模型之間的關係。 – 2011-04-26 15:34:30

+0

性能明智,這是否具有與通過關聯限制查詢相同的效果? (初學者在這裏) – noli 2011-07-15 03:25:01

2

那麼,可能有更好的方法,但我知道你可以使用實際的Arel條件(而不是ActiveRecord::Relation)在關聯中使用Arel的to_sql功能。

has_many :spam_comments, :class_name => 'Comment', :conditions => Comment.arel_table[:spammy].eq(true).to_sql 

您會注意到實際的Arel代碼不像ActiveRecord關係那麼精簡。

我確實在Rails master分支中發現了a comment,它引用了將Arel謂詞作爲條件傳遞,但代碼似乎不在3.0分支中。至少不是我能找到的。

相關問題