Ruby-on-rails 如何覆盖 rails 命名约定?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1185035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I override rails naming conventions?
提问by chrishomer
I have a model named "clothing" which I want to be the singlular (one piece of clothing). By default, rails says the plural is clothings. Right or wrong, I think it will be more readable if the plural is "clothes".
我有一个名为“服装”的模型,我想成为它的单数(一件衣服)。默认情况下,rails 说复数是服装。对还是错,我觉得如果复数是“衣服”会更易读。
How do I override the plural naming convention? Can I do it right in the model so I don't have to do it over and over? How will this change how routes are handled (I am using restful architecture)?
如何覆盖复数命名约定?我可以在模型中正确地做,这样我就不必一遍又一遍地做吗?这将如何改变路由的处理方式(我使用的是 Restful 架构)?
回答by Rich Seller
I'm no RoR expert, but did find a possible approach. From the referenced site you can add inflection rule inside the config/initializers/inflections.rbfile:
我不是 RoR 专家,但确实找到了可能的方法。从引用的站点,您可以在config/initializers/inflections.rb文件中添加屈折规则:
# Add new inflection rules using the following format
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'clothing', 'clothes'
end
回答by chrishomer
For rails 2.3.2 and maybe 2+, you need to do it a little different:
对于 rails 2.3.2 或者 2+,你需要做一些不同的事情:
ActiveSupport::Inflector.inflections do |inflect|
inflect.plural /^(ox)$/i, 'en'
inflect.singular /^(ox)en/i, ''
inflect.irregular 'octopus', 'octopi'
inflect.uncountable "equipment"
end
回答by Shan Valleru
Add this in your environment.rbfile if you are trying to stop database pluralization
environment.rb如果您试图停止数据库复数化,请将其添加到您的文件中
ActiveRecord::Base.pluralize_table_names = false
回答by JAGJ jdfoxito
With Ruby 2.2.2 windows or linux for me best solve was :
使用 Ruby 2.2.2 windows 或 linux 对我来说最好的解决方法是:
ActiveRecord::Base.pluralize_table_names = false
class Persona < ActiveRecord::Base
end
personas = Persona.all
personas.each do | personita |
print "#{personita.idpersona} #{personita.nombre}\n"
end
p Persona.count

