0

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

关系:

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

我需要过滤餐厅的所有 check_itemswhere category.uuid = '123123'

所以我有我的@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)}

但这似乎不起作用

4

1 回答 1

0

如果有人感兴趣,这似乎是我发现它起作用的唯一方法。

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

于 2013-05-27T12:51:30.070 回答