【问题标题】:Using a referenced model object in JBuilder Ruby on Rails在 JBuilder Ruby on Rails 中使用引用的模型对象
【发布时间】:2015-01-28 17:38:16
【问题描述】:

我正在尝试学习 Ruby on Rails,并且一直试图获得比我一直遵循的教程更复杂的 JSON 响应。

我有两个模型如下:

class Worker < ActiveRecord::Base
  has_many :tips
end

class Tip < ActiveRecord::Base
  belongs_to :worker
end

所以每个Worker都有很多tips。

我的控制器如下:

class WorkersController < ApplicationController

  skip_before_filter :verify_authenticity_token

  def index
    @workers= Worker.all
  end

  def show
    @worker= Worker.find(params[:id])
    @tips = @worker.tips
  end

end

class TipsController < ApplicationController

  skip_before_filter :verify_authenticity_token

  def index
    @tips = Tip.all
  end

  def show
    @tip = Tip.find(params[:id])
  end

end

正如您在 WorkersController 中看到的,我将 Worker 的所有提示分配给 @tips 变量。

现在我想以 JSON 格式返回这些信息,我正在使用部分来尝试实现这一点。

这是 Worker 部分:

json.(worker, :id, :name, :location, :image)

这里是部分提示:

json.(tip, :id, :title, :summary, :rating)

两者都在views/layouts/workers目录下

这是我真正想要返回的 JSON(它位于名为 show.json.jbuilder 的文件中:

json.worker do
  json.partial! 'worker', worker: @worker
  json.tips do
    json.partial! 'tip', tip: @tip
  end
end

但是这给了我一个 500 内部服务器错误。

如果我这样离开:

json.themepark do
  json.partial! 'themepark', themepark: @themepark
end

我得到了 JSON,但当然我缺少我需要的数据。我不确定接下来要采取什么步骤来尝试找出我做错了什么,所以想知道是否有人可以帮助我解决我的错误?

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4 jbuilder


    【解决方案1】:

    500 可能是因为您没有在workers_controller#show 中定义@tip

    为了成功渲染现有对象,您需要执行以下操作:

    json.worker do
      json.partial! 'worker', worker: @worker
      json.tips do
        json.partial! 'tip', collection: @tips, as: :tip
      end
    end
    

    【讨论】:

    • 这似乎奏效了,它给了我现在看起来像数据库错误的东西:) 我也尝试过以下方式 - json.array! 'tips', @tips, partial: 'tip', as: :tip 这也不起作用。使用集合比尝试使用 .array 创建它更好!功能?
    • 我相信这是一个偏好问题。
    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多