【问题标题】:Nested Objects with Inherited Resources具有继承资源的嵌套对象
【发布时间】:2011-07-21 13:28:35
【问题描述】:

首先,我喜欢inherited_resources

考虑以下几点:

class Job < ActiveRecord::Base
  has_many :inputs, dependent: :destroy
  has_one :output
end

class JobsController < InheritedResources::Base
  respond_to :json
end

当我请求 jobs/1.json 时,我只得到了作业对象的 JSON。我想要的也是要包含的输入和输出。我通常通过以下方式实现:

job.to_json(include: [:inputs,:output])

我的问题是使用 IR 实现这一目标的最佳方法是什么?现在,我只是覆盖显示,但我想知道是否有更优雅的方式?

谢谢!

【问题讨论】:

  • 也许你可以在模型中覆盖作业的 to_json,这样当 IR 调用它时,你会得到它的输入和输出

标签: ruby-on-rails json inherited-resources


【解决方案1】:

@corroded 让我走上了正轨。答案是在模型上覆盖 as_json。

具体来说,我做了以下事情:

  public

  def as_json(options={})
    super(include: [:inputs,:output])
  end

【讨论】:

    猜你喜欢
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2012-12-14
    相关资源
    最近更新 更多