私は3つのモデルを持っています
オプション:
class Option < ActiveRecord::Base
attr_accessible :key, :name
belongs_to :item_options
end
項目オプション
class ItemOption < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :item
belongs_to :option
end
および項目:
class Item < ActiveRecord::Base
has_many :item_options
has_many :options, :through => :item_options
end
そして、JSON形式でオプションを含むすべてのアイテムを返すためにコントローラーが必要なので、.includesを使用しようとしていますが、うまくいきません:
items = Item
.order('id')
.where(manufacturer)
.where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
:include => :options
)
結果にはオプションが含まれていませんが、コンソールに適切な DB リクエストがあることがわかります。ただし、to_json 内で :include を使用する場合にのみ機能します。
items = Item
.order('id')
.where(manufacturer)
.where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
:include => :options
)
最初の質問は、.include が機能しないように、何が間違っているのでしょうか?
しかし、コードの動作にも問題があります。item_options が定義済みアイテムの定義済みオプションの値を保持する場合、オプションはオプション名、オプション グループ ID などを格納するだけなので、オプションを item_options と結合する必要があります。そして、次のようにコードを拡張しようとしています:
items = Item
.order('id')
.where(manufacturer)
.where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
:include => {
:options => {
:joins => :item_options
}
}
)
それでも、item_options に結合されていないオプションを受け取ります。なんで?
また、オプトイン内で結合を使用する場合、アイテムが item_options に追加情報なしでロードされた場合、アイテムで has_many を定義する必要がありますか?
========== 更新:
options
今のところ、Items モデルのメソッドへの関係を置き換えただけです。
item = Item
.includes(:item_options)
.find(params[:id])
render :json => item.to_json(:methods => :options)
そしてアイテムモデルでは:
has_many :item_options
def options
self.item_options.select('item_options.value, options.name, options.is_feature, options.root').joins('left join options on options.id = item_options.option_id')
end
ただし、このソリューションが最適かどうかはわかりません。