繁体   English   中英

Rails中模型的辅助方法

[英]Helper methods for models in Rails

Rails中的模型是否有适当的辅助方法? 控制器和视图有辅助方法,但我不确定放置模型辅助方法的最佳位置。 除了向ActiveRecord::Base添加一个方法,我不想这样做。

更新 :似乎忧虑很有意义。 这是我想要的一个例子。 某些模型永远不会被删除,所以我添加一个总是抛出异常的回调:

before_destroy :nope
def nope
  raise 'Deleting not allowed'
end

有顾虑,我可以这样做吗?

class MyModel < ActiveRecord::Base
  include Undeletable
end

module Undeletable
    extend ActiveSupport::Concern

    included do 
      before_destroy :nope 
    end

    def nope
      raise 'Deleting not allowed'
    end
end

这是Rails这样做的方式吗?

如果要在model使用helper_method my_helper_method ,可以编写

ApplicationController.helpers.my_helper_method

如果您需要更多的灵活性,例如,如果您还需要覆盖某些方法,则可以执行以下操作:

class HelperProxy < ActionView::Base
  include ApplicationController.master_helper_module

  def current_user
    #let helpers act like we're a guest
    nil
  end       

  def self.instance
    @instance ||= new
  end
end

然后使用

HelperProxy.instance.my_helper_method

如果你有强烈的神经,你也可以尝试将ApplicationController.master_helper_module直接包含在你的model

via:makandracards的帖子。

供您参考: http//railscasts.com/episodes/132-helpers-outside-views

如果您要问的是在rails 4.2中将多个模型共享的代码放在何处,那么标准答案必须是使用问题: 如何在Rails 4中使用问题

但是,有一些很好的论据(例如这个 )只是使用标准的rails模块包含,并且扩展为marek-lipka建议。

我强烈建议不要在模型中使用ApplicationController辅助方法,因为你将导入很多不必要的行李。 在我看来,这样做通常是一种难闻的气味,因为这意味着你没有分离MVC元素,并且你的应用程序中存在太多的相互依赖性。

如果需要通过添加仅在视图中使用的方法来修改模型对象,那么请查看装饰器。 例如https://github.com/drapergem/draper

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM