Rails controller action duplication

242 Views Asked by At

I have a controller show action which does some stuff and renders a view but due to some custom routing, I need a totally different action in a totally different controller to perform the same stuff and render the same view.

I don't really wish to duplicate the code. Is there somewhere I can put it and call it from both locations?

Edit:

I basically need to run the following from Collection#Show AND also from Gallery#SplitUrl:

@collection = Collection.find_by_id(params[:id])
if @collection.has_children?
  @collections = @collection.children
else
  redirect_to [@collection, :albums]
end

I cannot just redirect_to Collection#Show at the end of Gallery#SplitUrl as the redirect causes my custom URL's to be lost as it's a new request.

2

There are 2 best solutions below

1
On

You could put the view content into a partial (/app/views/home/_example.html.erb) and then use the render "example" command in the HomeController.

The "some stuff" code you talk about could be put into a helper file /app/helpers/... to save you from duplicating code in the two separate controllers although it could depend on what the code is trying to do in the first place.

http://guides.rubyonrails.org/layouts_and_rendering.html

This might provide more information on the subject in general.

1
On

I think the simplest approach would be to add a route definition for your new url and map that to your existing controller's action.

Something like follows:

# config/routes.rb

# Existing resource
resources :foos

# The resource in question
resources :bars do 
  get :show, controller: 'foos', action: 'show', as: bar_foo_common_show
end

Note that this will give you /bar/:id, where id represents a bar resource. So in your foo#show action, your finder needs to be executed on appropriate class. This is when a few lines of hacky codes get added, for e.g. checking for request referer.

I think moving the common code to a function in possibly application_controller and calling that function from both show action would be cleaner approach, but based on my understanding you already have a similar scenario except for the common code in application_controller, and would like to try out a different approach!