Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unscope an associated record in Rails 3

I'm having some trouble getting scoping to work correctly in rails.

My models:

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


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

When I call the following:

feeds = Feed.includes(:user)

I want to skip over the default_scope for users. so I tried:

feeds = Feed.unscoped.includes(:user)

But this is not removing the scope from users. Any suggestions on how I can get this to work? Thank you

like image 486
AnApprentice Avatar asked Jan 21 '13 19:01

AnApprentice


1 Answers

You can accomplish this by using .unscoped in block form, as documented here:

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

Note that whether or not the default scope applies depends on whether or not you're inside the block when the query is actually executed. That's why the above uses .all, forcing the query to execute.

Thus, while the above works, this won't - the query is executed outside the .unscoped block and the default scope will apply:

User.unscoped do
  @feeds = Feed.includes(:user)
end
@feeds #included Users will have default scope
like image 62
MrTheWalrus Avatar answered Oct 27 '22 04:10

MrTheWalrus