如何使一个方法可用于所有控制器? 以及如何所有型号?

我是Rails的新手,并编写了一个方法to_csv ,我将它放在products_controller.rb中,但我希望它也可用于所有其他控制器。 这样做的首选方法是什么? 它在application.rb中吗?

同样,如果我在某个model.rb中编写方法,如何在所有模型之间共享该方法?

application_controller将是这个地方。 如果对于模型,也许您可​​以在模块中编写,然后在您的模型中包含您要使用的模块。

1)尝试ActiveRecord :: Base monkeypatching。 初始化程序目录是收集所有这些小任务的最佳位置

所以,试试/config/initializers/active_record_extension.rb,

 class ActiveRecord::Base def self.export(parameters) #your csv logic goes here end end 

要么

2)创建主类,用于inheritance所有active_record模型

例如/models/your_class.rb

 class YourClass < ActiveRecord::Base def self.export(parameters) #your csv logic goes here end end class CsvDB < YourClass end 

您也可以在不inheritanceActiveRecord::Base情况下创建单独的模型,并在该特定模型中定义csv方法。 从任何控制器只需拨打电话

 model_name.method_name(parameters) 

例如,在模型CsvDB中:

 class CsvDB def export(parameters) # your csv logic goes here end end 

从任何控制器只需打电话

 CsvDB.export(parameters)