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!
Sep 12 ’11

Associations with Conditions

You can specify ActiveRecord Associations with a condition on them:

class Post
  has_many :comments
  has_many :published_comments,
           :class_name => "Comment",
           :conditions => { :published => true }
end

One possible use-case is that you can use these associations to eager load only a subset of the associated records:

post = Post.find(1, :include => :published_comments)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", 1]]
# SELECT "comments".* FROM "comments" WHERE "comments"."post_id" IN (1) AND ("comments"."published" = 't')

Read more about this in the API docs about ActiveRecord::Associations.

6 notes 0 comments

  1. buy-steroids--uk reblogged this from rubyquicktips
  2. 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