Skip to content

Instantly share code, notes, and snippets.

@abachman
Created October 12, 2010 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abachman/621644 to your computer and use it in GitHub Desktop.
Save abachman/621644 to your computer and use it in GitHub Desktop.
Conditional query chaining in Rails 3
# I want a list of 6 non-administrators who are not the
# current user only if someone is logged in. Otherwise,
# don't check current_user's id.
# instead of this:
if user_signed_in?
@other_users = User.non_admin.limit(6).where("name IS NOT NULL")
else
@other_users = User.non_admin.limit(6).where(['id != ?', @user.id]).where("name IS NOT NULL")
end
# I can write:
@other_users = User.non_admin.limit(6).tap {|query|
query.where(['id != ?', @user.id]) if user_signed_in?
}.where("name IS NOT NULL")
# The "if user_signed_in?" inside the tap block means I am
# conditionally modifying the query midstream. The same
# object is passed out the other side of the tap statement
# whether or not the additional .where is ever evaluated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment