【问题标题】:Where/how to include geography helper method - Rails?在哪里/如何包含地理辅助方法 - Rails?
【发布时间】:2015-09-04 00:29:35
【问题描述】:

我有一个辅助方法 states_list,它返回一组我想在我的 Rails 应用程序的几个不同位置访问的美国州,包括:

  • 用户型号:validates :state, inclusion: { in: states_list }
  • 用户模型规范:测试此验证

这些将在用户模型之外的其他地方重复使用。我想知道存储此辅助方法的正确位置在哪里,以及如何从模型和测试中访问它。 (我最初的想法是在 helpers 目录中的 GeographyHelper 文件中,但我读到这些文件专门用于查看帮助程序......)谢谢!

【问题讨论】:

    标签: ruby-on-rails rspec model helper


    【解决方案1】:

    最好将您的states_list 方法放在它自己的模块中并将其包含在您的用户模型中。创建模块的优点是您的关注点可以很好地分离和可重用(以防您想验证其他模型中的状态。

    1) 通过进入您的 /lib 目录并为您的自定义模块创建一个目录(我们在此将其称为 custom_modules)来创建一个放置模块的位置。

    2) 创建你的模块文件:/lib/custom_modules/States.rb

    3) 编写你的模块:

    module CustomModules
    
      module States
    
        def states_list
          #your logic here
        end
    
      end
    end
    

    4) 将新的 States 模块包含在您的 User 模型或您想要此功能的任何其他模型中。

    class User < ActiveRecord::Base
    
      include CustomModules::States
    
      validates :state, inclusion: { in: states_list }
    end
    

    【讨论】:

    • 嗯,它不起作用 - 获取:undefined local variable or method us_states' for #<0x007fecdc244930>
    • &lt;&lt;
    【解决方案2】:

    您可以将此方法存储在application helperuser model 中。

    【讨论】: