2013-01-21 90 views
6

我在使用Rails正確工作時遇到了一些麻煩。如何在Rails 3中查找相關記錄

我的模型:

class User < ActiveRecord::Base 
    default_scope :conditions => 'users.deleted_at IS NULL' 


class Feed < ActiveRecord::Base 
    belongs_to :user, :foreign_key => :author_id 

當我撥打以下:

feeds = Feed.includes(:user) 

我想跳過了用戶的default_scope。所以我嘗試過:

feeds = Feed.unscoped.includes(:user) 

但是,這並不是從用戶中刪除範圍。關於如何讓這個工作的任何建議?謝謝

+1

http://stackoverflow.com/questions/3963124/default -scope-and-associations或http://stackoverflow.com/questions/4758145/how-to-use-unscoped-on-associated-relations-in-rails3幫助? –

+1

可悲的是,沒有。第一個已經過時了。第二個不詳細使用包括。 – AnApprentice

回答

14

您可以通過以方框圖的形式使用.unscoped,做到這一點的記載here

User.unscoped do 
    @feeds = Feed.includes(:user).all 
end 

注意,默認的範圍是否適用取決於你是否是塊裏面的時候查詢實際上是執行。這就是爲什麼上面使用.all,迫使查詢執行。

因此,雖然上述工作,這不會 - 該查詢的.unscoped塊外執行,並且默認範圍將適用:

User.unscoped do 
    @feeds = Feed.includes(:user) 
end 
@feeds #included Users will have default scope 
+1

不確定我在追隨,給我如何查詢Feed,包括:用戶的表現。這將如何適用? – AnApprentice

+0

剛剛嘗試將此添加到user.rb,有沒有影響? – AnApprentice

+1

@AnApprentice您問過如何避免在'.includes'中列出的關聯中使用默認範圍。這是如何。您仍然渴望加載用戶,但不要將其限制爲未被刪除的用戶。這不是你想要的嗎? – MrTheWalrus