【问题标题】:Show won't render correct json显示不会呈现正确的 json
【发布时间】:2014-10-24 01:34:04
【问题描述】:

我正在尝试在我的车辆控制器中使用以下内容在我的 JSON 中包含一些额外的位:

  # GET /vehicles/1
  # GET /vehicles/1.json
  def show
    @vehicle = Vehicle.find(params[:id])

    respond_to do |format|
      format.json { @vehicle.to_json(:methods => [:product_applications_with_notes], :include => [:product_applications]) }
    end
  end

车辆模型既有方法:product_applications_with_notes,也有关系has_many: :product_applications。但是,当我向http://localhost:3000/vehicles/1 运行请求时,JSON 输出如下:

{ “身份证”:1, “制造”:“讴歌”, “型号”:“全部”, “年”:2001, "body_style": "汽车", "created_at": "2014-10-22T20:06:00.157Z", “updated_at”:“2014-10-22T20:07:09.827Z” }

它不显示包含的额外位。为什么?

【问题讨论】:

  • 这可能不是问题,但请尝试加载:product_applications,即Vehicle.includes(:product_applications).find(params[:id])
  • @Ali 没有骰子。它没有改变输出。

标签: ruby-on-rails ruby json


【解决方案1】:

尝试覆盖 Vehicle 模型中的 as_json 方法。

类似:

  def as_json(options=nil)
    json_hash = super(options)
    json_hash[:product_applications] = product_applications

    json_hash
  end

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 2020-12-19
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2019-08-02
    • 2023-03-29
    相关资源
    最近更新 更多