Matthew Rathbone
Matthew Rathbone

Reputation: 8269

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

Upvotes: 6

Views: 5499

Answers (2)

fuzzyalej
fuzzyalej

Reputation: 5973

Also would work respond_with {:uuid => @p.uuid}, :location => nil

Upvotes: 4

tjwallace
tjwallace

Reputation: 5688

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 }

Upvotes: 7

Related Questions