在Rails Helper中检索模型类型

时间:2019-02-04 09:14:25

标签: ruby-on-rails

Rails 5中的帮助器类(例如UserHelper)是否可以访问与(User)相关的模型类型?

我有一些共享的逻辑AddFilter,需要模型类型正常工作。我现在强制执行方法filter_for来指定使用哪种模型:

module AddFilter
  def filter_for
    raise "filter_for not implemented"
  end

  #...other code
end

当前,我在许多助手中都包含了这种逻辑:

module UserHelper
  include AddFilter

  def filter_for
    User
  end
end

是否可以直接在AddFilter中检索模型类型?

1 个答案:

答案 0 :(得分:1)

显然,由于控制器中包含辅助程序,因此可以使用控制器的功能:

# add_filter.rb
def filter_for
    controller_path.classify.constantize
end

先指定了retrieves the controller pathclassifies the name,然后是tries to find the constant

仍然感觉很hacky,更好的解决方案受到赞赏!