我需要Rails最佳实践的建议。实际上,在我的应用程序中,对于我的cars_controller和contacts_controller,我需要为new、create、edit和update操作的两个控制器加载数据(如下所示):
@countries = Country.all
@types = Type.all
@departments = Department.all
@models = Model.all // This one is only needed on contacts_controller那些将被填充到选择框中。由于我需要在每个new、create、edit和update操作上重复它,所以我在application_controller中创建了一个load_resource:
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但是,如果我想为其他控制器加载其他数据,我真的觉得很脏呢?我想知道这方面是否有最佳做法?
我试过使用演示程序模式,但是由于这些数据不是特别附加在任何东西上,因为它们只是选择框中的数据,所以它真的不起作用。
谢谢你的帮忙
发布于 2013-10-04 03:36:52
我可以看到两个可能的改进,第一,您不需要在每个操作上加载资源,其次,您可以使用缓存来提高性能。
不要在每个动作上加载资源
假设您遵循标准REST约定,如果这些资源用于您的下拉列表,则在create和update中不需要它们。您只需要在new和edit中使用它们,因为只有这两个操作向用户显示一个页面。create和update是表单调用的操作,将重定向到其他页面。
与其将其添加到您的application_controller中,不如向您的contacts_controller和cars_controller添加一个before_filter
contacts_controller.rb
before_filter :load_resources_for_dropdowns, :only => [:new, :edit]
def load_resource_for_dropdowns
....
end使用缓存
此外,如果您担心从数据库加载资源对性能的影响,可以考虑对其使用缓存。例如,如果您的国家列表从未更改,您可以安全地执行以下操作:
country.rb
def get_all_cached
Rails.cache.fetch('all_countries') { Country.all }
endcontacts_controller.rb
before_filter :load_resources_for_dropdowns, :only => [:new, :edit]
def load_resource_for_dropdowns
@countries = Country.get_all_cached
end如果您的国家确实发生了变化,您可以在发生变化时添加检查以清除缓存:
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 }
endhttps://stackoverflow.com/questions/19171161
复制相似问题