Rails 3 respond_with, route constraints and resources

强颜欢笑 提交于 2019-12-11 04:19:47

问题


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]


来源:https://stackoverflow.com/questions/5269086/rails-3-respond-with-route-constraints-and-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!