【发布时间】: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