次のリソースがあります: - レストラン - カテゴリ - 項目 - チェック項目
関係:
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_items をフィルタリングする必要がありますwhere 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)}
しかし、これはうまくいかないようです