fabrik42/acts_as_api

resource written with plural but it should not

apneadiving opened this issue · 4 comments

Hi,

I'm running accross a problem using:

  • Rails 3.0.10
  • acts_as_api 0.3.11
  • Mongoid

Controller:

respond_with @project, :api_template => :v1_public

Model:

  api_accessible :v1_public do |template|
    Project.accessible_attributes.to_a.each do |key|
      template.add key.to_sym
    end
  end

I wonder why, the rendered json is prepended with projects instead of project. Indeed, it recognizes it's not an array:

 {"projects":
   {
     "name": "foo"
    #other attributes of the lonely project here 
   }
 }

Hey,
this is strange, I need to look into it when I find some time.

Meanwhile you can force the resource name by passing the :root parameter:

respond_with @project, :api_template => :v1_public, :root => :project

Cheers,

Chris

Ok, I see, so should use two different templates, one for plural, the other one for singular.

Thanks for your answer, please keep me updated whenever you update the gem.

I was just reading your code and did some tests in console:

project = Project.first
project.respond_to?(:collection_name) #=> true

So according to https://github.com/fabrik42/acts_as_api/blob/master/lib/acts_as_api/rendering.rb#L45 the root is set to projects.

But I made some other tests:

projects = Project.limit 2
projects.respond_to? :collection_name #=> true
projects.respond_to? :model_name      #=> true

so it should work properly there.

Playing with ActiveRecord from another app:

u = User.first
u.respond_to? :collection_name      # => false
u.respond_to? :model_name           # => false
u.class.respond_to? :model_name  # => true

So your gem works fine with ActiveRecord but we found a bug for Mongoid.

No perfect idea, but I would test with something like respond_to? :ancestors.
In our current context:

  • when true: collection
    *when false: instance

Ok, sorry for the delay but this issue should be fixed by now :)

Let me know if you experience further problems!