I’m looking for someone to confirm the following as a bug in Rails
1.0 before I post it to Trac.
If I use eager loading on an association that has conditions defined,
the conditions are ignored.
The following example illustrates the problem. I have two tables:
create_table “blogs”, :force => true do |t|
t.column “name”, :string
end
create_table “posts”, :force => true do |t|
t.column “blog_id”, :integer
t.column “subject”, :string
t.column “published”, :boolean
end
The model for blogs looks like this:
class Blog < ActiveRecord::Base
has_many :posts
has_many :published_posts, :class_name => ‘Post’, :foreign_key
=> ‘blog_id’, :conditions => ‘published = 1’
end
Now add some sample data for blogs:
example:
id: 1
name: Example
and for posts:
published:
id: 1
blog_id: 1
subject: Published
published: 1
unpublished:
id: 2
blog_id: 1
subject: Unpublished
published: 0
The problem is that:
Blog.find(:all, :include => :published_posts).first.published_posts
returns all the posts for the blog, not just the published ones. The
SQL generated looks like this:
SELECT posts.id
AS t1_r0, posts.blog_id
AS t1_r1,
blogs.id
AS t0_r0, posts.subject
AS t1_r2,
blogs.name
AS t0_r1, posts.content
AS t1_r3,
posts.published
AS t1_r4
FROM blogs LEFT OUTER JOIN posts ON posts.blog_id = blogs.id
The following, on the other hand, returns just the posts marked as
published:
Blog.find(:all).first.published_posts
If anyone wants a simple sample project to test this, let me know and
I’ll tar up my example.
Cheers,
Pete Y.