开发者

Active Record calls join scopes on reload?

I have two scopes with right outer joins declared on my User model. Here they are

scope :users_with_school, joins("right outer join profiles on profiles.user_id = users.id     right outer join profiles_schools开发者_Go百科 on profiles.id = profiles_schools.profile_id").uniq
scope :full_profile,  joins("right outer join profiles on profiles.user_id = users.id right outer join profiles_schools on profiles.id = profiles_schools.profile_id where users.pic_file_name is not null and profiles.occupation is not null and birthday is not null and profiles.desc is not null and hometown is not null ").uniq

My problem is that when I reload my console and call User.all I see both of these scopes being executed (i.e. I see the SQL in the console window) but I don't see any other scopes. It doesn't seem to effect the result of the query however I'm still confused as to why they get executed in the first place.

Here is an example ruby-1.9.2-p290 :023 > reload! Reloading...

 => true 
ruby-1.9.2-p290 :024 > User.all.count
User Load (296.5ms)  SELECT "users".* FROM "users" right outer join profiles on     profiles.user_id = users.id right outer join profiles_schools on profiles.id = profiles_schools.profile_id
 User Load (7.4ms)  SELECT "users".* FROM "users" right outer join profiles on profiles.user_id = users.id right outer join profiles_schools on profiles.id = profiles_schools.profile_id where users.pic_file_name is not null and profiles.occupation is not null and birthday is not null and profiles.desc is not null and hometown is not null
 User Load (435.8ms)  SELECT "users".* FROM "users" 

=> xxxx Users

Then when I execute the query again without reloading , it just executes the User.all query

ruby-1.9.2-p290 :025 > User.all.count
User Load (606.7ms)  SELECT "users".* FROM "users" 
=> xxxx Users (the same as above)

So, my question is, why is this happening and why is it only happening to these two scopes (out of 30 or so), the only difference I can see is that they are right outer joins

Obviously I don't want these scopes to run every time I load a User class, at present it seems to be just when I reload everything though. Any insight ?

(using postgres, rails 3.1.1 ruby 1.9.2)


I believe you are seeing this because .uniq acts on and returns an array, and so your scope does not return a scope.

Try using SQL "DISTINCT" in a .select() after the join.

scope :users_with_school, joins("right outer join ...").select("DISTINCT users.id")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜