Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 622
Matthew Rathbone Avatar asked Dec 16 '10 04:12

Matthew Rathbone


1 Answers

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 }
like image 129
tjwallace Avatar answered Sep 29 '22 09:09

tjwallace