Eager loading Rails 3 ActiveRecord Model with conditions on the base table -


i'm trying result: posts published , have specific tag, , include tags (to avoid n+1)

here code:

@posts = post.includes(   :tags ).where(   :status => 'published', :tags => { :name => params[:tag_name] } ).order(   'published_at desc' ) 

here rails s output:

parameters: {"tag_name"=>"family"} post load (1.1ms) select "posts"."id" t0_r0, "posts"."title" t0_r1, "posts"."body" t0_r2, "posts"."published_at" t0_r3, "posts"."excerpt" t0_r4, "posts"."slug" t0_r5, "posts"."created_at" t0_r6, "posts"."updated_at" t0_r7, "posts"."status" t0_r8, "tags"."id" t1_r0, "tags"."name" t1_r1, "tags"."created_at" t1_r2, "tags"."updated_at" t1_r3 "posts" left outer join "posts_tags" on "posts_tags"."post_id" = "posts"."id" left outer join "tags" on "tags"."id" = "posts_tags"."tag_id" "posts"."status" = 'published' , "tags"."name" = 'family' order published_at desc completed in 102ms

here error message:

/home/sam/.rvm/gems/ruby-1.8.7-p334@global/gems/activerecord-3.0.6/lib/active_record/attribute_methods.rb:44:in `eval': missing attribute: status 

i can see sql posts.status column aliased t0_r8, how can respect condition?

edit query had, work:

@posts = post.joins(   :tags ).where(   "posts.status = ? , tags.name = ?",     "published",     params[:tag_name] ).order(   "published_at desc" ) 

hmmm maybe didn't understand way activerecord works; solution came with:

@posts = post.includes(   :tags ).joins(   :tags ).where(   "posts.status = ? , tags.name ?",   "published",   params[:tag_name] ).order(   "published_at desc" ).paginate(   :per_page => 5,   :page => params[:page],   :order => "published_at desc" ) 

my mistake in assuming joins , includes duplicate functionality, apparently not:

post load (1.7ms) select "posts".* "posts" inner join "posts_tags" on "posts_tags"."post_id" = "posts"."id" inner join "tags" on "tags"."id" = "posts_tags"."tag_id" (posts.status = 'published' , tags.name 'family') order published_at desc tag load (1.1ms) select "tags".*, t0.post_id the_parent_record_id "tags" inner join "posts_tags" t0 on "tags".id = t0.tag_id (t0.post_id in (7,6,4))


Comments