如何覆盖rails命名约定?

chr*_*mer 73 ruby-on-rails naming-conventions pluralize

我有一个名为"服装"的模特,我想成为单件(一件衣服).默认情况下,rails表示复数是衣服.对或错,我认为如果复数是"衣服",它将更具可读性.

如何覆盖复数命名约定?我可以在模型中做到这一点,所以我不必一遍又一遍地做吗?这将如何改变路由的处理方式(我使用的是宁静的架构)?

Ric*_*ler 123

我不是RoR专家,但确实找到了可能的方法.从引用的站点,您可以在config/initializers/inflections.rb文件中添加变形规则:

# Add new inflection rules using the following format 
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'clothing', 'clothes'
end
Run Code Online (Sandbox Code Playgroud)

  • 实际上,您的自定义变形应该位于config/initializers/inflections.rb中 (45认同)
  • 对于像我这样懒惰的人:`ActiveSupport :: Inflector.inflections do | inflect |`如果它没有找到Inflector就可以了 (3认同)

chr*_*mer 28

对于rails 2.3.2和2+,你需要做一些不同的事情:

ActiveSupport::Inflector.inflections do |inflect|
    inflect.plural /^(ox)$/i, '\1\2en'
    inflect.singular /^(ox)en/i, '\1'

    inflect.irregular 'octopus', 'octopi'

    inflect.uncountable "equipment"
end
Run Code Online (Sandbox Code Playgroud)


Sha*_*eru 5

environment.rb如果要尝试停止数据库复数,请在文件中添加此项

ActiveRecord::Base.pluralize_table_names = false
Run Code Online (Sandbox Code Playgroud)