Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Aug 29 ’11

Dynamic Scopes

Rails 2.3 introduced dynamic named scopes. Dynamic scopes are created for each attribute in your model, prefixed by scoped_by_:

# A dynamic scope for a single attribute
Post.scoped_by_category('tech')
# => SELECT "posts".* FROM "posts" WHERE "posts"."category" = 'tech'

# One for multiple attributes, concatenated by '_and_'
Post.scoped_by_category_and_author_id('tech', 1)
# => SELECT "posts".* FROM "posts" WHERE "posts"."category" = 'tech' AND "posts"."author_id" = 1

The difference to dynamic finders (e.g. Post.find_by_category('tech')) is, that you can chain these together and add additional conditions - just like with any named scope:

Post.scoped_by_category('tech').all(:select => "id, title")
# => SELECT id, title FROM "posts" WHERE "posts"."category" = 'tech'

15 notes 0 comments

  1. rubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus