HXH
HXH

Reputation: 1663

About the Rails route namespace

In my Rails app,I have a controller /app/api/mem_controller.rb

class MemController < AplicationApiController
  before_filter :mem_login?
  def follows
    _mem = MemAccount.find(params[:id])
    render json: {
      :items=> _mem.follow_mems.limit(page_size).offset(page * page_size),
      :count=> _mem.follow_mems.length
    }.as_json(:methods=>['avatar_url'])
  end
end

I add a config in application.rb

config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

My route is:

namespace :api do 
  get "mem/:id/follows" => 'mem#follows'
end

Now I want the route is /api/mem/1/follows.

But this raise error:

uninitialized constant Api

If I take out the namespace wrapper,/mem/1/follows will do work.

Then I want to know how can I realize /api/mem/1/follows throuth the route keywords namespace,I need the api prefix to avoid the conflict.

I don't want to place the api folder under /app/controller/

Upvotes: 0

Views: 212

Answers (1)

Marko Krstic
Marko Krstic

Reputation: 1447

yes sure, because you are using namespace. try this:

class Api::MemController < AplicationApiController
    ...
end

and that controller MemController should be:

app/controllers/api/mem_controller.rb

if you don't want to create sub-folder, then you should use scope instead of namespace in routes.rb, and in that case you can keep your MemController without changing (I mean you don't need to add Api::)

scope '/api' do

end

more explanation: http://guides.rubyonrails.org/routing.html

Upvotes: 2

Related Questions