【问题标题】:How to do a has_many through with a condition based on joining another table to the join table如何通过基于将另一个表连接到连接表的条件来执行 has_many
【发布时间】:2013-02-07 04:52:46
【问题描述】:

我需要在 Rails 中建立 has many_through 关系,其中返回的唯一记录是连接表附加到另一个表中的特定记录的记录。

我在 SQL 中尝试过,但它不起作用。下面的 SQL 关系如何以活动记录的形式表达?

以下是模型:

class User
  has_many :organisation_roles
  has_many :organisations,
           through: :organisation_roles
end 

class OrganisationRole
  belongs_to :user
  belongs_to :organisation
  belongs_to :role
end

class Role
  has_many :organisation_roles
end

class Organisation

  has_many :organisation_roles
  has_many :roles, through: :organisation_roles
  has_many :users, through: :organisation_roles

  # This doesn't work
  has_many :members, 
           class_name: 'User', 
           through: :organisation_roles,
           finder_sql: Proc.new {
             %Q{
               SELECT u.*
                 FROM users u, organisation_roles ors, roles r
                WHERE ors.organisation_id = #{id} AND r.name = 'member'
       }
  }

  # This doesn't either
  has_many :managers, 
           through: :organisation_roles, 
           source: :user, 
           conditions: { organisation_roles: { role: { name: 'manager' }}}

end

【问题讨论】:

    标签: ruby-on-rails has-many-through rails-activerecord


    【解决方案1】:

    找到了解决办法,虽然用的是实例方法,但不是has_many:

    class Organisation
      # other stuff
    
      def members
        users.joins(:roles).where("roles.name = 'member'")
      end
    end
    
    class User
      # other stuff
    
      has_many :roles,
               through: :organisation_roles
    end
    

    【讨论】:

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