Reputation: 2393
I need advice with Rails best practices. Actually in my application, for my cars_controller
and my contacts_controller
I need to load datas (below) for both controllers in new
, create
, edit
and update
actions :
@countries = Country.all
@types = Type.all
@departments = Department.all
@models = Model.all // This one is only needed on contacts_controller
Those gonna be populate into select box. Since I need to repeat it on each new
, create
, edit
and update
actions, I created a load_resource
into my application_controller
:
application_controller.rb
def load_resources
@countries = Country.all
@types = Type.all
@departments = Department.all
@models = Model.all // This one is only needed on contacts_controller
end
However, it really feel dirty to me as, what if I want to load other data for other controllers? I would like to know if there is best practicies for that?
I tried using a Presenter pattern but since those datas are not particularly attached to anything since they are just data in select box, it really didn't work.
Thanks for your help
Upvotes: 0
Views: 72
Reputation: 2125
I can see two possible improvements, firstly you don't need to load the resource on every action, secondly you can use caching to improve performance.
Assuming your are following the standards REST conventions, if these resources are for your dropdowns, you don't need them in create
and update
. You only need them in new
and edit
, since only these two actions display a page to the user. create
and update
are the actions invoked by your form and would redirect to some other page.
Instead of adding it to your application_controller
, I would just add a before_filter
to your contacts_controller
and cars_controller
contacts_controller.rb
before_filter :load_resources_for_dropdowns, :only => [:new, :edit]
def load_resource_for_dropdowns
....
end
Also, if you are concerned about the performance impact of loading the resources from the database, you can consider using caching for it. For example, if your countries list never changes, you can safely do the following:
country.rb
def get_all_cached
Rails.cache.fetch('all_countries') { Country.all }
end
contacts_controller.rb
before_filter :load_resources_for_dropdowns, :only => [:new, :edit]
def load_resource_for_dropdowns
@countries = Country.get_all_cached
end
If your countries does change, you can add a check to clear the cache whenever something changes:
country.rb
after_save :clear_cache
def clear_cache
Rails.cache.delete('all_countries')
end
def get_all_cached
Rails.cache.fetch('all_countries') { Country.all }
end
Upvotes: 3