zdenko.s
zdenko.s

Reputation: 1032

No route matches {:action=>"show" ... missing required keys: [:id]

Seeing many question related to this but none of them gives answer to my problem. I have Rails api application without ActiveRecord support. It is easy to reproduce problem. Follow steps: Create rails api site without ActiveRecord support

rails new test001 -O --api

Change folder to test001 and run:

rails g scaffold testapp id name

Create model file testapp.rb in app/models folder

class Testapp
  include ActiveModel::Model
  attr_accessor :id, :name, :created_at, :updated_at
  def self.all
    t1 = Testapp.new(:id =>111, name: "t111")
    return [t1]
  end
end

Start server

rails s

Using postman REST client create GET request

http://localhost:3000/testapps.json

It fails with error ActionView::Template::Error (No route matches {:action=>"show", :controller=>"testapps", :format=>:json, :id=>#<Testapp:0x00000005411518 @id=111, @name="t111">} missing required keys: [:id]):

I have dummy implementation for POST, PUT, GET 1 item and all works. Here is dummy implementation of GET 1 item (/testapps/x.json)

  def self.find(p)
    return Testapp.new(:id =>p, name: "t123")
  end

What is the problem with GET all (/testapps.json)?

Upvotes: 1

Views: 406

Answers (1)

zdenko.s
zdenko.s

Reputation: 1032

Found solution. Problem is scaffold generated index.json.jbuilder file:

json.array!(@testapps) do |testapp|
  json.extract! testapp, :id, :id, :name
  json.url testapp_url(testapp, format: :json) #REMOVE
end

It added line json.url testapp_url(testapp, format: :json) for no reason. json.extract! deserialized object already. Removing line solved problem. I still do not know why testapp_url(testapp, format:json) caused error. Checking Rails Routing document http://guides.rubyonrails.org/routing.html

Upvotes: 2

Related Questions