4

I'm working on a rails app that serves some json and I'm having hard time understanding what is going on in the code below (simplified for the purpose of understanding the issue).

module Api
  class ProjectController < ApplicationController
    respond_to :json

    def show
       x = {"id"=>17, "name"=>"abc", "version"=>1}
       respond_with x.to_json, status: 200
    end

    def create
      x = {"id"=>17, "name"=>"abc", "version"=>1}
      respond_with x.to_json, status: 200
    end
  end
end

The show action works fine but when I call the create action I get

NoMethodError (undefined method '{"id":17,"name":"abc","version":1}_url' for Api::ProjectsController:0x007fbb2294cd18)

Why do I get this error while show works just fine? is it because create makes a post instead of a get?

How can I solve it?

Thanks for your help and have a nice day.

Sig
  • 5,476
  • 10
  • 49
  • 89
  • Why are you returning ` Hash` object rather than an instance of the `Project` class? – Ryan Bigg Oct 02 '13 at 03:38
  • it is because the project object is in a second app. The second app returns is as json `def create respond_with Project.create(project_params) end` to the main app (the 1 I have issue with) and the main app forwards it to the original caller. – Sig Oct 02 '13 at 03:53
  • 1
    Looks like that adding location:nil solves the issue `respond_with x.to_json, status: 200, location: nil` Why is this happening? Thanks – Sig Oct 02 '13 at 03:58
  • see this http://stackoverflow.com/questions/7303551/rails-respond-with-acting-different-in-index-and-create-method – tihom Oct 02 '13 at 06:12
  • Thanks Tihom for your reply – Sig Oct 02 '13 at 09:47

1 Answers1

2

The issue is that your controller is in a module (Api). That affects the namespace, and thus the routing; you must include that namespace as part of what you pass to respond_with.

Normally, I'd direct you to this stackoverflow answer (credit goes there). But since you are using a hash instead of a model, this answer might be more applicable.

Note how Rails is trying to call a ..._url method. The ... is your hash, in JSON format. You need to help Rails here on how to render.

Community
  • 1
  • 1
Tyler Collier
  • 11,489
  • 9
  • 73
  • 80