如何使用基于将另一个表连接到连接表的条件来执行has_many

时间:2013-02-21 18:19:03

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

我需要在Rails中创建一个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

1 个答案:

答案 0 :(得分:0)

找到一个解决方案,虽然使用实例方法,但不是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