简体   繁体   中英

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

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:

undefined method `model_name' for NilClass:Class

If I change the respond_with call to something simpler I still get errors, eg:

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!

PS, my routes file looks like this:

  match 'join' => 'game#join', :via => :post

I believe the respond_with methods requires you to pass the resource ( @p ) as an argument. Here is some documentation for the method .

Try this:

respond_with @p, :only => [:uuid]

You could also render json like this:

render :json => { :uuid => @p.uuid }

也可以使用respond_with {:uuid => @p.uuid}, :location => nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM