1

我需要在 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
4

1 回答 1

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
于 2013-02-21T21:09:30.850 回答