【问题标题】:Rails ActiveRecord::find Join statement issueRails ActiveRecord::find Join 语句问题
【发布时间】:2009-06-16 14:16:51
【问题描述】:

为什么下面的rails声明

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

翻译成这个(使用 2x 相同的连接)

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') 

只是好奇。

【问题讨论】:

    标签: ruby-on-rails activerecord join


    【解决方案1】:

    我不需要加入 roles_users,因为插件已经这样做了一次...

    感谢您的帮助。

    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
    

    【讨论】:

      【解决方案2】:

      我没有看到重复的连接,我看到 rails 尝试使用命名约定来连接 roles_users 和 users 导致 rails 正在寻找 roles_users_users 表。

      因为您的模型中有用户和角色之间的关系,所以您不必指定加入角色用户

      【讨论】:

      • 忘了说这不是一个 .. 多对多关系表,而是一个真正的模型,它自己有 1 个用户并属于 1 个角色
      【解决方案3】:

      我不知道为什么它会产生这么多的 SQL 代码。需要从您的模型中查看更多代码。像这样的东西可能会减少代码/复杂性并产生优化的 SQL 代码:

      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 }})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多