Rails通过联合表过滤资源一对多

时间:2013-05-24 15:50:17

标签: ruby-on-rails

我有以下资源: - 餐厅 - 类别 - 项目 - 检查项目

关系:

class Restaurant < ActiveRecord::Base
  has_many :items
  has_many :categories
  has_many :check_items

class Category < ActiveRecord::Base
  belongs_to :restaurant
  has_many :items

class Item < ActiveRecord::Base
  belongs_to :restaurant
  belongs_to :category

class CheckItem < ActiveRecord::Base
  belongs_to :item

我需要过滤餐馆where category.uuid = '123123'

的所有check_items

所以我有@restaurant.check_items。我如何将它们连接在一起基本上实现这个SQL查询:

SELECT * from checkitem
INNER JOIN item ON(checkitem.item_id = item.id)
INNER JOIN category ON(category.id = item.category_id)
WHERE category.restaurant_id = 1 AND category.uuid = '123123'
LIMIT 20;

我尝试过范围:

#already have my restaurant resource here with id 1
@restaurant.check_items.by_item_category params[:category_uuid]

在我的模特中我会:

class CheckItem < ActiveRecord::Base
  ...
  scope :by_item_category, -> value { joins(:item).by_category value }

class Item < ActiveRecord::Base
  ...
  scope :by_category, -> value { joins(:category).where('%s.uuid = ?' % Category.table_name, value)}

Buut这似乎不起作用

1 个答案:

答案 0 :(得分:0)

如果有人感兴趣的话,这似乎是我发现这个工作的唯一方式。

CheckItem.joins(:item =&gt; {:category =&gt;:restaurant})。where('category.uuid =?and restaurant.id =?',123123,1)