1

我有 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?

========== 更新:

现在我只是替换了optionsItems 模型中与方法的关系:

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

但是,不知道这个解决方案是否是最优的。

4

1 回答 1

1

您调用to_json的是哈希而不是模型,而哈希对包含或连接一无所知。

尝试将您的 json 选项放在模型上

data = items.offset(offset).as_json(include: :options)
render json: {data: data, total: items.count}

另外,我认为你Option belongs_to :item_options应该是Option has_many :item_options

在 as_json 中使用 :include 是对 ActiveModel json 序列化程序的指令,告诉它在输出 JSON 中包含来自关联的数据。

ActiveModel::Serializers::JSON ( github )

连接和包含方法是 ActiveRecord 的一部分,用于添加连接条件和执行预加载。

ActiveRecord 加入
ActiveRecord 包括

于 2013-02-16T17:48:43.380 回答