Note that there are some explanatory texts on larger screens.

plurals
  1. POEager loading Rails 3 ActiveRecord Model with conditions on the base table
    primarykey
    data
    text
    <p>I'm trying to get this result: All Posts that are published AND have a specific tag, and include the tags (to avoid n+1)</p> <p>Here is my code:</p> <pre><code>@posts = Post.includes( :tags ).where( :status =&gt; 'published', :tags =&gt; { :name =&gt; params[:tag_name] } ).order( 'published_at DESC' ) </code></pre> <p>Here is the rails s output:</p> <p><code>Parameters: {"tag_name"=&gt;"family"} Post Load (1.1ms) SELECT "posts"."id" AS t0_r0, "posts"."title" AS t0_r1, "posts"."body" AS t0_r2, "posts"."published_at" AS t0_r3, "posts"."excerpt" AS t0_r4, "posts"."slug" AS t0_r5, "posts"."created_at" AS t0_r6, "posts"."updated_at" AS t0_r7, "posts"."status" AS t0_r8, "tags"."id" AS t1_r0, "tags"."name" AS t1_r1, "tags"."created_at" AS t1_r2, "tags"."updated_at" AS t1_r3 FROM "posts" LEFT OUTER JOIN "posts_tags" ON "posts_tags"."post_id" = "posts"."id" LEFT OUTER JOIN "tags" ON "tags"."id" = "posts_tags"."tag_id" WHERE "posts"."status" = 'published' AND "tags"."name" = 'family' ORDER BY published_at DESC Completed in 102ms</code></p> <p>Here is the error message:</p> <pre><code>/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 </code></pre> <p>I can see from the SQL that the <code>posts.status</code> column is aliased to <code>t0_r8</code>, but how can I get it to properly respect my condition?</p> <p><strong>EDIT</strong> query that I had, that does work:</p> <pre><code>@posts = Post.joins( :tags ).where( "posts.status = ? AND tags.name = ?", "published", params[:tag_name] ).order( "published_at DESC" ) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload