[英]respond_with not working in ruby on rails. Why?
I have a post method called join that should do the following: 1) create a new object 2) respond with a json object 我有一个名为join的post方法,它应该执行以下操作:1)创建一个新对象2)使用json对象进行响应
Here is my code: 这是我的代码:
class GameController < ApplicationController
respond_to :json
def join
@p = Player.new(:name => params[:name])
@p.save!
respond_with({:uuid => @p.uuid})
end
end
For some reason, the respond_with call always fails with this error: 出于某种原因,respond_with调用始终失败并显示以下错误:
undefined method `model_name' for NilClass:Class
If I change the respond_with call to something simpler I still get errors, eg: 如果我将respond_with调用更改为更简单的东西,我仍然会收到错误,例如:
respond_with "hello"
yields this error: 产生此错误:
undefined method `hello_url' for #<GameController:0x1035a6730>
What am I doing wrong?? 我究竟做错了什么?? I just want to send them a JSON object back!
我只想向他们发送一个JSON对象!
PS, my routes file looks like this: PS,我的路线文件看起来像这样:
match 'join' => 'game#join', :via => :post
I believe the respond_with
methods requires you to pass the resource ( @p
) as an argument. 我相信
respond_with
方法要求您将资源( @p
)作为参数传递。 Here is some documentation for the method . 以下是该方法的一些文档 。
Try this: 尝试这个:
respond_with @p, :only => [:uuid]
You could also render json like this: 你也可以这样渲染json:
render :json => { :uuid => @p.uuid }
也可以使用respond_with {:uuid => @p.uuid}, :location => nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.