Rails 3 respond_with, route constraints and resour

2019-08-03 17:18发布

问题:

I'm building a versioned API, so I have the following nested controllers:

  • ApiController < ApplicationController
  • Api::V1Controller < ApiController
  • Api::V1::EventsController < Api::V1Controller

The API is accessed via a subdomain. I have the following routes:

  constraints(:subdomain => "api") do
    scope :module => 'api' do
      namespace :v1 do
        resources :events
      end
    end
  end

This produces the type of URL I want (/v1/events).

The problem I'm facing is when using responds_with in Api::V1::EventsController. Just doing something as simple as the below fails with the error too few arguments:

def index
    @events = Event.all
    respond_with(@events)
end

I know respond_with is meant to be used with resources, but I'm not sure how the events resource should be accessed from the constrained, scoped, and namespaced route. I can output other things (such as current_user), just not an array of events. Help?

Update:

Here's what works:

# a single resource
def index
    @event = Event.all.first
    respond_with @event
end

# an array of a completely different resource
def index
    @user = User.all
    respond_with @user
end

So maybe it has something to do with the Event model, specifically collections vs. arrays. I'll keep investigating.

回答1:

Try to use something like:

respond_with [:v1, @events]