我有一个名为“服装”的模型,我想成为唯一的(一件衣服)。默认情况下,rails 说复数是服装。对与错,我认为如果复数是“衣服”会更易读。
如何覆盖复数命名约定?我可以在模型中正确地做,这样我就不必一遍又一遍地做吗?这将如何改变路由的处理方式(我使用的是 restful 架构)?
我有一个名为“服装”的模型,我想成为唯一的(一件衣服)。默认情况下,rails 说复数是服装。对与错,我认为如果复数是“衣服”会更易读。
如何覆盖复数命名约定?我可以在模型中正确地做,这样我就不必一遍又一遍地做吗?这将如何改变路由的处理方式(我使用的是 restful 架构)?
我不是 RoR 专家,但确实找到了一种可能的方法。从引用的站点,您可以在config/initializers/inflections.rb
文件中添加变形规则:
# Add new inflection rules using the following format
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'clothing', 'clothes'
end
对于 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
environment.rb
如果您试图停止数据库复数,请将其添加到您的文件中
ActiveRecord::Base.pluralize_table_names = false
使用 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