class People
belongs_to :client
has_many :store_roles
end
class Roles
has_many :store_roles
end
class StoreRole
belongs_to :role
belongs_to :people
belongs_to :store
end
class Client
has_many :stores
has_many :people
end
class Store
belongs_to :client
has_many :store_roles
has_many :roles, :through => :store_roles
end
假设所有这些类都继承自ActiveRecord::Base
;)
您将需要设置迁移和数据库结构来反映这些关系。对于每个belongs_to
有一个:object_id
表上的字段引用相应表的 ID。
您的查询需要类似于:
Store.find(1).roles.find(:all, :conditions => ["store_roles.person_id = ?", 1])
我可能会向商店模型添加一个方法,以使这变得更容易:
def roles_for(person_id)
roles.find(:all, :conditions => ["store_roles.person_id = ?", person_id])
end
这样您就可以使用以下方式找到角色:
Store.find(1).roles_for(1)
或者,更好的是:
def self.roles_for(store_id, person_id)
Role.find(:all, :joins => :store_roles, :conditions => ["store_roles.store_id = ? AND store_roles.person_id = ?", store_id, person_id])
end
这将我们的查找器更改为:
Store.roles_for(1, 1)
我想说最后一种方法是最理想的,因为它仅导致单个查询,而其他每个选项在每个角色查找中对数据库执行两个查询(一个用于查找存储,一个用于获取角色) person_id)。当然,如果您已经实例化了 Store 对象,那么这没什么大不了的。
希望这个答案足够了:)