Rails ActiveRecord :: find Go to Release Message

Why the following rails statement

User.find(:all, :joins => [:roles,:roles_users], 
          :conditions => { :roles => { :name => 'subscriber', 
                                       :authorizable_id => self.id, 
                                       :authorizable_type => self.class.to_s }})

Translates to this (with 2x the same connection)

SELECT "users".* FROM "users" 
    JOIN "roles_users" ON ("users"."id" = "roles_users"."user_id") 
    JOIN "roles" ON ("roles"."id" = "roles_users"."role_id") 
    JOIN "roles_users" roles_users_users ON roles_users_users.user_id = users.id 
  WHERE ("roles"."authorizable_id" = 4 AND "roles"."name" = 'subscriber' AND "roles"."authorizable_type" = 'Howto') 

Just curious.

+3
source share
3 answers

I did not need to join role_users, because the plugin already did this once ...

Thank you for your help.

has_many :users, :finder_sql => 'SELECT DISTINCT users.* FROM users INNER JOIN roles_users ON user_id = users.id INNER JOIN roles ON roles.id = role_id WHERE authorizable_type = \'#{self.class.base_class.to_s}\' AND authorizable_id = #{id}', :counter_sql => 'SELECT COUNT(DISTINCT users.id) FROM users INNER JOIN roles_users ON user_id = users.id INNER JOIN roles ON roles.id = role_id WHERE authorizable_type = \'#{self.class.base_class.to_s}\' AND authorizable_id = #{id}', :readonly => true
+1
source

I don’t see the duplicate connection, I see that the rails are trying to use naming conventions to join the role_users and users, resulting in the rails looking for the role_users_users table.

since you have relationships between users and roles in your model, you do not need to specify a union of user_users

0

I have no idea why this would create such SQL code. You will need to see more code from your model. Something like this might be less code / complex and create optimized SQL code:

class Server < ActiveRecord::Base
  has_and_belongs_to_many :roles, :join_table => :roles_users
end

User.all(:include => :roles, :conditions => {:roles => { :names => 'subscriber', :authorizable_id => self.id, :authorizable_type => self.class.to_s }})
0
source

Source: https://habr.com/ru/post/1710579/


All Articles