模型和助手中的常用方法 [英] Common method in model and helper
问题描述
- 将模型方法移到
application_helper.rb
文件 - 我的模型通过在我的ActiveRecord模型顶部添加
include ApplicationHelper
来调用application_helper方法
功能明智,它的工作原理。但这是一个很好的做法吗?
我的模型看起来像这样:
类客户端< ActiveRecord :: Base
include ApplicationHelper
end
写入包括ApplicationHelper
到你的模型是不好的做法,因为ApplicationHelper是一个很好的地方,你需要在你的意见中的大量帮助功能。这些函数将最终导入为模型的实例方法。这些功能大多与您的模型无关,如果它们依赖于 params
或请求
等内容,将无法正常工作。这里有两个选项:
选项1:
您可以定义在 Client
类中的方法,然后从视图中调用它,如下所示:
code> class Client< ActiveRecord :: Base
def self.my_class_method
end
def my_instance_method
end
end
然后在您的视图中:
<%= Client.my_class_method% >
<%= @ client.my_instance_method%>
选项2:
在 lib
中创建一个单独的模块,并将其包含在您需要的位置。文件名应与自动加载的模块名称相匹配。
在 lib / my_module.rb
中:
模块MyModule
def my_method
end
end
在您的模型中:
客户端ActiveRecord :: Base
包含MyModule
def other_method
my_method
end
end
将该模块包含在ApplicationHelper中,以便您可以查看所有视图:
模块ApplicationHelper
包括MyModule
end
然后在您的视图中,您可以轻松调用它:
<%= my_method%>
I have a common method that exists in my model because it is called by my model. Retrospectively, my view also requires this model method. In order to accomplish this, I have:
- moved the model method to the
application_helper.rb
file - my model calls the application_helper method by adding
include ApplicationHelper
at the top of my ActiveRecord model
Functionality wise, it works. But is this good practice?
My Model looks like this:
class Client < ActiveRecord::Base
include ApplicationHelper
end
Writing include ApplicationHelper
in to your model is bad practice because ApplicationHelper is a nice place to put tons of helper functions you need in your views. These functions will end up being imported as instance methods of your model. These functions are mostly unrelated to your model and will not work if they depend on things like params
or request
. Here are two other options:
Option 1:
You can just define the method inside the Client
class, and then call it from the view, like this:
class Client < ActiveRecord::Base
def self.my_class_method
end
def my_instance_method
end
end
And then in your view:
<%= Client.my_class_method %>
<%= @client.my_instance_method %>
Option 2:
Make a separate module in lib
and include it in the places you need it. The file name should match the module name for auto-loading to work.
In lib/my_module.rb
:
module MyModule
def my_method
end
end
In your model:
class Client < ActiveRecord::Base
include MyModule
def other_method
my_method
end
end
Include the module in ApplicationHelper so it is available to all your views:
module ApplicationHelper
include MyModule
end
Then in your view you can call it easily:
<%= my_method %>
这篇关于模型和助手中的常用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!