我有两个基本模型:体育场和所有者
这两个模型之间的关系是:
体育场:
belongs_to :owner
所有者:
has_many :stadiums
这里的事情是,所有者也有类别关联,这里是 owner_category 模型的来源。
所有者:
has_and_belongs_to_many :owner_categories,
:join_table => 'l_owners_owner_categories',
OwnerCategory :
has_and_belongs_to_many :owners, :join_table => 'l_owners_owner_categories'
基本上,
OwnerCategory表如下所示:
id,name
1,sport
2,kids
所以,我的问题是:
鉴于我让用户选择城市和类别,我如何从该城市获得所有体育馆 < strong>所有者具有给定的类别?
例如:
如果我有以下体育场:
id,name,city,owner_id
1,'soccer stadium','New York',5
2,'music stadium','New York',4
2,'music stadium','San Francisco',4
以下所有者:
id,name
4, 'John'
5, 'Peter'
以下OwnersCategories表:
id,name,description
1,'sports','this category is associated with stadiums that support sports'
2,'music','this category is associated with stadiums that support music'
以下连接表:
owner_id,owner_category_id
5, 1
当用户选择“纽约”和“体育”时,它应该给这个体育场:
1,'soccer stadium','New York',5
答案 0 :(得分:0)
尝试这样的事情(警告:未经测试):
Stadium.joins(:owner).joins(:owner => :owner_categories)
.where(:city => "New York").where("owners_categories.name = ?", "sports")
答案 1 :(得分:0)
class Stadium < ActiveRecord::Base
scope :for_city, lambda { |city_name| where(:city => city_name) }
scope :for_owner_category,
lambda { |owner_category_id|
joins("INNER JOIN owners ON owners.id = stadium.owner_id" +
" INNER JOIN l_owners_owner_categories ON l_owners_owner_categories.owner_id = owners.id").
where("l_owners_owner_categories.owner_category_id = :category_id",
:category_id => owner_category_id)
}
end
Stadium.for_city("New York").for_owner_category(1)