Where/how 包含地理辅助方法 - Rails?

Where/how to include geography helper method - Rails?

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

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

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

您可能最好将 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 模块包含在您的用户模型或任何其他您想要此功能的模型中。

class User < ActiveRecord::Base

  include CustomModules::States

  validates :state, inclusion: { in: states_list }
end