Tagged as with_scope

edit delete favorite
Posted by eric on Nov 01, 2007
with_scope lets you bind a block of code operating on an active record model to a particular subset of that model’s collection. For instance, using the standard blog application example, if I have a controller method that performs a series of operations on a single user’s articles I would need to pass in the user id condition on every operation. with_scope lets us extract that parameter.
# Notice we have to pass in the 'user_id' on both the find and create method.
def create_avoid_dups
  user_id = current_user.id

  # Find all user's posts
  user_posts = Post.find(:all, :conditions => ["user_id = ?", user_id])

  # Do some logic ...

  # then create new
  @post = Post.create(:body => params[:body], :user_id => user_id)
end

# with_scope lets us extract that parameter:
def create_avoid_dups
  Post.with_scope(:find => {:conditions => "user_id = #{current_user.id}"},
                  :create => {:user_id => current_user.id}) do

    # Find all user's posts
    # No longer need user_id condition since we're in scope
    user_posts = Post.find(:all)

    # Do some logic ...

    # then create new, without specifying user_id
    @post = Post.create(:body => params[:body])
  end
end
 
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Tags
Spacer