问题
in my User model I have a scope:
scope :with_tournament_entrees, :include => :registers, :conditions => "registers.id IS NOT NULL"
I wanted to see the SQL being generated by this scope and it produces:
"SELECT \"users\".* FROM \"users\" WHERE (registers.id IS NOT NULL)"
I don't see any mention of the include parameter I added and returns an error if executed in the console as raw SQL with the help of ActiveRecord::Base.connection.execute
. If I was to query User.with_tournament_entrees in the console on the other hand it produces correct 8 records I need with no errors whatsoever, looking at the log I see the SQL statement being executed...
SELECT "users"."id" AS t0_r0, "users"."email" AS t0_r1,
"users"."encrypted_password" AS t0_r2, ....
"registers"."id" AS t1_r0, "registers"."competition_id" AS t1_r1,
"registers"."user_id" AS t1_r2 ...
FROM "users" LEFT OUTER JOIN "registers" ON "registers"."user_id" = "users"."id"
WHERE (registers.id IS NOT NULL)
Which looks about right, so just to double check I copy the SQL and wrap it inside ActiveRecord::Base.connection.execute
and it executes perfectly - except now instead of getting 8 records like I did when I called the scope I get 12 records.
What gives? It's executing the exact same SQL right? So why am I getting different results? I'm using a PostgreSQL database.
Oh and I know you shouldn't use scopes in Rails 3, which is why I'm trying to get at the SQL so I can figure out how to ActiveRecordify(?) it.
回答1:
This is explained by 2 facts: 1. Adding joins effectively means you get a result set row per every valid combination of user row and a register row. So, if some user has 2 records in registers table - you get two rows for that user record. 2. Active Record knows the above and is capable of "merging" rows, so that you get one user with two registers, not two same users with one register each.
This way, running bare query yields the results from MySQL point of view, which is 12 rows. And ActiveRecord processes them down to 8 records, as some of the rows contain same user's fields, just multiple registers' ones.
Hope this helps :)
来源:https://stackoverflow.com/questions/11127980/rails-3-possible-erb-bug-when-executing-raw-sql-calling-scopes