【问题标题】:Respond_with JSON @object sends associated objects, not @object?Respond_with JSON @object 发送关联对象,而不是@object?
【发布时间】:2011-12-14 15:47:03
【问题描述】:

如何控制 .json 请求中返回的对象?在下面的示例中,我得到的是关联对象,而不是主要对象——产品,而不是公司:

class Company
  has_many :products
  include Enumerable

class Product
  belongs_to :company

controller Company
  respond_to :html, :json

  def show
    @company = Company.find(1)
    respond_with @company
  end

**respond_with @company   ==>  json of products, not company!**
respond_with @company.id ==> json of :id

【问题讨论】:

  • 你能把你控制器的相关部分贴出来吗?
  • @Robin 我添加了控制器。我想我发现混入 Enumerable 会导致问题。事实证明,转换为 JSON 将检索可枚举对象的相关集合,而不是对象本身。

标签: ruby-on-rails-3.1


【解决方案1】:

似乎在 Rails 上使用 to_json,如果对象具有通过 Enumerable 关联的集合,您将获得对象的关联集合。在问题中,如果您删除 Enumerable 的包含,则 json 中返回的对象将只是该对象。但是在包含 Enumerable 的情况下,json 会产生完整的集合,在本例中为 products。要解决此问题,您似乎必须删除 Enumerable。

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 2021-04-15
    相关资源
    最近更新 更多