Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one action for multiple models

I have about 5 models that behave very similarly. In fact, I'd like them to share an action for displaying them. For example, for models Car, Truck, Van I want to have a definition like:

[Car, Truck, Van].each do |Model|
  action_for Model do #I made this up to show what I mean
    def index
      @model = Model.all
      @model_names = @model.map(&:name).join(', ')
    end
  end
end

How would I do this so I'm not defining the same action in multiple controllers? (Which isn't very DRY) Would it be in the application_controller? And if it's not too much to ask, how could I do this so they also share the view?

UPDATE

It would be preferred if this can be outside the individual controllers. If I can get this to work right, I'd like to not even have to generate the individual controllers.

like image 210
Kyle Macey Avatar asked Mar 11 '12 04:03

Kyle Macey


1 Answers

Would something like this work for you?

module Display
  def index
    m = self.class.to_s.chomp('Controller').classify.constantize
    @model = m.all
    @model_names = @model.map(&:name).join(', ')
  end
end

In the controllers:

class CarsController < ApplicationController
  include Display 
end

class TrucksController < ApplicationController
  include Display 
end

class VansController < ApplicationController
  include Display 
end

Edit: an attempt to do this without individual controllers

class DisplaysController < ApplicationController
  def index
    @model = params[:model].constantize.all
    @model_names = @model.map(&:name).join(', ')
  end
end

routes.rb

match "display" => "display#index", :as => :display

In a view

link_to "Display Cars", display_path(:model => "Car")
link_to "Display Trucks", display_path(:model => "Truck")
link_to "Display Vans", display_path(:model => "Van")

Note: If you've heard of extend for modules and are wondering why/when to use include vs extend, see What is the difference between include and extend in Ruby? (basically include is for instances, extend for class methods).

like image 124
Kyle Avatar answered Sep 28 '22 06:09

Kyle