在 Rails 上使用 JBuilder Ruby 中的引用模型对象

Using a referenced model object in JBuilder Ruby on Rails

我正在尝试在 Rails 上学习 Ruby,并且一直试图获得比我一直关注的教程稍微复杂的 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 但当然我缺少我需要的数据。我不确定接下来要采取什么步骤来弄清楚我做错了什么,所以想知道是否有人可以帮助我解决我的错误?

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