I have a nested resource that belongs to many different models. For instance:
resources :users do
resources :histories, only: [:show]
end
resources :publications do
resources :histories, only: [:show]
end
resources :events do
resources :histories, only: [:show]
end
In the HistoriesController
, I want to find the parent object, though I'm having trouble thinking of a dry way to handle this. At the moment, the best I can come up with is:
if params[:user_id].present?
@parent = User.find(params[:user_id])
elsif params[:publication_id].present?
@parent = Publication.find(params[:publication_id])
elsif . . . .
I've got literally dozens of models I have to branch through in this way, which seems sloppy. Is there a better (perhaps baked-in) approach that I'm not considering?
The way I am doing this is adding the parent model class name as a default param in the route.
For the question example this should be something like:
resources :users, model_name: 'User' do
resources :histories, only: [:show]
end
resources :publications, model_name: 'Publication' do
resources :histories, only: [:show]
end
resources :events, model_name: 'Event' do
resources :histories, only: [:show]
end
This will add the model name in the params hash.
Then in the controller/action you can get your parent model like:
params[:model_name].constantize # Gives you the model Class (eg. User)
and the foreign key like:
params[:model_name].foreign_key # Gives you column name (eg. user_id)
So you can do something like:
parent_class = params[:model_name].constantize
parent_foreing_key = params[:model_name].foreign_key
parent_object = parent_class.find(params[parent_foreing_key])
not really a solution but you can get away with
parent_klasses = %w[user publication comment]
if klass = parent_klasses.detect { |pk| params[:"#{pk}_id"].present? }
@parent = klass.camelize.constantize.find params[:"#{klass}_id"]
end
if you are using a convention between your parameter name and your models
As an alternative to the accepted answer, you could use a dynamic route like this:
get ':item_controller/:item_id/histories/:id', to: 'histories#show'
This should then should allow you to access the parent class something like this in your histories_controller.rb
parent_controller = params[:item_controller]
parent_class = parent_controller.singularize.camelize.constantize
@parent = parent_class.find(params[:item_id])
You may be able to add a constraint on item_controller in the routes as well if you need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With