我有以下资源: - 餐厅 - 类别 - 项目 - 检查项目
关系:
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)}
但这似乎不起作用