ActiveRecordモデルを使用して、特定の条件に適合するネストされたアソシエーションが返されたレコードの内側にあるのを防ぐために、アソシエーションをトップレベルまですべてフィルタリングします。ネストされたhas_manyアソシエーションをフィルタリングするActiveRecordクエリ
私はこれをより良く説明しましょう。 、SuperCategoriesControllerで
class SuperCategory < ActiveRecord::Base
attr_accessible :name
has_many :categories
end
class Category < ActiveRecord::Base
attr_accessible :name
belongs_to :super_category
has_many :sub_categories
has_many :books
end
class SubCategory < ActiveRecord::Base
attr_accessible :name
belongs_to :category
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :sub_category
belongs_to :category
attr_accessible :show_me #boolean
end
私が持っている:私は、次のモデルを持っている
/super_categories.json
エンドポイントを叩く
class SuperCategoriesController < ApplicationController
def index
@super_categories = SuperCategory.all #here is where I want to query
respond_with(@super_categories)
end
end
、私は以来、JSON形式でツリー全体でこのようなものを得るでしょう部分的に私.jbuilderは、ネストされた団体のすべての追加:私は、私はそれがPARAMを渡す場合、コントローラでやってみたい何
[
{
name: "supercategory1",
categories: [
{
name: "category1",
books: [
{ show_me: true },
{ show_me: true },
{ show_me: false }
]
},
{
name: "category2",
sub_categories: [
{
name: "subcategory1",
books:[
{ show_me: false }
]
}
]
}
]
},
{
name: "supercategory2",
categories: [
{
name: "category3",
books: [
{ show_me: false }
]
}
]
}
]
ようshow_me = true
の場合は、show_me == false
の本を持つ書籍、サブカテゴリ、カテゴリ、スーパーカテゴリのいずれも表示しません。ここで私が試したものです:
class SuperCategoriesController < ApplicationController
def index
if params[:show_me] == true
@super_categories = SuperCategory.joins(:categories).joins(:sub_categories).where(:books => { show_me: true })
end
respond_with(@super_categories)
end
end
私は:books
に:sub_categories
に:categories
に参加する方法がわからないので、これはエラーを生成します。基本的には
[
{
name: "supercategory1",
categories: [
{
name: "category1",
books: [
{ show_me: true },
{ show_me: true }
]
}
]
}
]
、私は@super_category.categories
のみshow_me == true
本を入れ子にしているそれらのカテゴリがあるはず呼び出すとき:私は結果があることをしたいと思います。同様に、書籍があるサブカテゴリがある場合は、show_me == true
、それもそれらを返す必要があります。 .joins
と.where
のActiveRecordの組み合わせがありますか?
私は理由 '&' –
のここでの構文エラーを取得しています&ちょうど答えで2つの交互にコードに追加する必要がseperatingされていません –