I am new to rails and have a tricky routing question. I have a resource with a nested collection that maps to the controller of the type for the nested collection. However the name of the collection does not map to the controller which I want to route the request to.
Basically the User model has many followers and followings. These 2 collections map to the Follow model which has a follows controller with standard crud methods.
user.rb:
class User < ActiveRecord::Base
has_many :followers, class_name: Follow, foreign_key: :user_id, dependent: :destroy
has_many :followings, class_name: Follow, foreign_key: :follower_id, dependent: :destroy
end
follow.rb:
class Follow < ActiveRecord::Base
belongs_to :user, counter_cache: :followers_count
belongs_to :follower, class_name: 'User', counter_cache: :followings_count
attr_accessible :user, :user_id, :follower, :follower_id
validates_presence_of :user_id, :follower_id
validates_uniqueness_of :user_id, scope: :follower_id
end
follows_controller.rb:
def index
respond_with @follows
end
routes.rb:
resources :users do
resources :followers, :controller => "follows"
resources :following, :controller => "follows"
end
rake routes:
api_v1_user_followers GET /api/v1/users/:user_id/followers(.:format) api/v1/follows#index
POST /api/v1/users/:user_id/followers(.:format) api/v1/follows#create
new_api_v1_user_follower GET /api/v1/users/:user_id/followers/new(.:format) api/v1/follows#new
edit_api_v1_user_follower GET /api/v1/users/:user_id/followers/:id/edit(.:format) api/v1/follows#edit
api_v1_user_follower GET /api/v1/users/:user_id/followers/:id(.:format) api/v1/follows#show
PUT /api/v1/users/:user_id/followers/:id(.:format) api/v1/follows#update
DELETE /api/v1/users/:user_id/followers/:id(.:format) api/v1/follows#destroy
api_v1_user_following_index GET /api/v1/users/:user_id/following(.:format) api/v1/follows#index
POST /api/v1/users/:user_id/following(.:format) api/v1/follows#create
new_api_v1_user_following GET /api/v1/users/:user_id/following/new(.:format) api/v1/follows#new
edit_api_v1_user_following GET /api/v1/users/:user_id/following/:id/edit(.:format) api/v1/follows#edit
api_v1_user_following GET /api/v1/users/:user_id/following/:id(.:format) api/v1/follows#show
PUT /api/v1/users/:user_id/following/:id(.:format) api/v1/follows#update
DELETE /api/v1/users/:user_id/following/:id(.:format) api/v1/follows#destroy
I tried adding the :controller => 'follows' and that does correctly map both nested collection routes to the follows_controller. However I get this error:
Started GET "/api/v1/users/2/following?auth_token=qhcT6CSHi3S7KrEnJtq6" for 10.0.1.72 at 2013-04-22 09:52:43 -0600
ActionController::RoutingError (uninitialized constant Api::V1::FollowingController):
Any ideas on how to correctly solve this problem would be greatly appreciated.
Thanks,