Reputation: 806
I have the models Dad, Mom and Kid. I'm already using the kid's index
action for Dad and made another action in the Kids controller called mom_index
for Mom's since a kid belongs to a mom and a dad.
Right now the Dad's route goes to:
dad_kids GET /dads/:dad_id/kids(.:format) kids#index
Because of:
resources :dads do
resources :kids
end
I need my Mom's route to go to:
mom_kids GET /moms/:mom_id/kids(.:format) kids#mom_index
But doing this:
resources :moms do
resources :kids
end
Uses the kid's index action which is already being used by the dad. How can I get it to do this using the Kids mom_index
action instead?
Upvotes: 2
Views: 70
Reputation: 76774
You could just use an if
statement to check whether the request is for dads
or moms
etc:
#app/controllers/kids_controller.rb
Class KidsController < ApplicationController
def index
if params[:mom_id].present?
# mom logic
elsif params[:dad_id].present?
#dad logic
end
end
end
An alternative would be to set different controllers (however this is not recommended as it's not DRY):
#config/routes.rb
resources :moms do
resources :moms_kids, as: "kids" #-> domain.com/moms/:mom_id/kids
end
Upvotes: 3
Reputation: 4686
You are better off either having the kids
controller know how to deal with being used by either the dads or moms namespace or making two separate resources called dads_kids
and moms_kids
.
So for the first option you would leave what you have as far as routes but make the kids controller action smarter/overloaded.
For the second option you would do:
resources :dads do
resources :dads_kids
end
resources :moms do
resources :moms_kids
end
Then you would have 2 controllers dads_kids_controller.rb
and moms_kids_controller.rb
.
Upvotes: 2