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.

5
  • Why are you returning ` Hash` object rather than an instance of the Project class? Commented Oct 2, 2013 at 3: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. Commented Oct 2, 2013 at 3: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 Commented Oct 2, 2013 at 3:58
  • see this stackoverflow.com/questions/7303551/… Commented Oct 2, 2013 at 6:12
  • Thanks Tihom for your reply Commented Oct 2, 2013 at 9:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.