Rails 3 Possible ERB Bug When Executing Raw SQL/Calling Scopes?

烈酒焚心 提交于 2019-12-12 02:30:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!