London
London

Reputation: 15274

Rails reuse existing controller

There is a PartsController in my webapp and it works wonderfully well. It sends the right data to view so the view can render charts/stats/data etc. it and everything is full working order.

Now I've got another functionality in my app where I can combine parts into a product. And now I've got a ProductController which I want basically to retain exact the same behavior as parts controller, meaning I'd like to reuse views which exist from my parts controller but just send different data to view. PartsController would send one data and ProductController would send other data to the view but of course they would be of a same type.

What is the best way to do this? Maybe for productcontroller to inherit the parts controller? is this even possible in rails to override certain methods in controller but to use the same views?

Upvotes: 0

Views: 412

Answers (1)

Alex D
Alex D

Reputation: 30445

It sounds like you don't want to share the controller logic between PartsController and ProductController, just the views. If so, put the templates in a common directory, and in the controllers, do this to render:

 # imagine the templates are in app/views/products
 render 'products/action_name'

If you additionally want to share controller logic, there are a couple options:

  1. Both inherit from a common superclass
  2. One inherits from the other (and overrides selected methods)
  3. Both include a common Module

Upvotes: 1

Related Questions