简体   繁体   中英

named_scope width has_many association and count

I have models:

class User < ActiveRecord::Base
  has_many :user_skills
end

class UserSkill < ActiveRecord::Base
  belongs_to :user  

  named_scope :rated, :conditions => "count_raters > 0"  
end

I want to get count of rated skills.

current_user.user_skills.rated.cont

It works fine, but the generated SQL is a very strange.

SELECT count(*) AS count_all FROM `user_skills` WHERE (((count_raters > 0) AND (`user_skills`.user_id = 988988934)) AND (`user_skills`.user_id = 988988934)) 

Why does it past twice user_id? How to avoid double passing the user_id field?

I can't answer the why.

But there is absolutely no need to avoid this, because the internal optimization your (My|Postgre)SQL(ite) server should remove that by default, and it shouldn't have any influence to the time spend on this query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM