我有 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
)
结果不包含选项,但我在控制台中看到有适当的数据库请求。但是,只有当我在 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 连接的选项。为什么?
另外,如果我在 optoins 中使用连接,如果它们在 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
但是,不知道这个解决方案是否是最优的。