1

我有两个基本模型:StadiumOwner

这两个模型之间的关系是:

体育场:_

belongs_to :owner

业主:_

has_many :stadiums

这里的问题是,所有者还关联了类别,这就是owner_category模型的用武之地。

业主:_

has_and_belongs_to_many :owner_categories,
                          :join_table => 'l_owners_owner_categories',

所有者类别

has_and_belongs_to_many :owners, :join_table => 'l_owners_owner_categories'

基本上,

OwnerCategory 表如下所示:

id,name
1,sport
2,kids

所以,我的问题是:

鉴于我让用户选择一个城市和一个类别,我将如何从所有者拥有给定类别的那个城市获得所有体育场

例如:

如果我有以下体育场:

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
4

2 回答 2

0

尝试这样的事情(警告:未测试):

Stadium.joins(:owner).joins(:owner => :owner_categories)
.where(:city => "New York").where("owners_categories.name = ?", "sports")
于 2012-04-26T21:15:56.943 回答
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)
于 2012-04-26T21:19:36.980 回答