模型和助手中的常用方法 [英] Common method in model and helper

查看:97
本文介绍了模型和助手中的常用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常见的方法存在于我的模型,因为它被我的模型调用。回想起来,我的观点也需要这种模式的方法。为了实现这一点,我有:


  1. 将模型方法移到 application_helper.rb 文件

  2. 我的模型通过在我的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:

  1. moved the model method to the application_helper.rb file
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆