我有一个名为"clothing"的模型,希望它成为单数形式(一件衣服)。默认情况下,Rails将其复数形式设定为"clothings"。无论对错,我认为如果复数形式是"clothes"会更易读。
我该如何重写复数命名规则?我能否在模型中直接进行操作,以免反复修改?这将如何改变路由的处理方式(我正在使用RESTful架构)?
我有一个名为"clothing"的模型,希望它成为单数形式(一件衣服)。默认情况下,Rails将其复数形式设定为"clothings"。无论对错,我认为如果复数形式是"clothes"会更易读。
我该如何重写复数命名规则?我能否在模型中直接进行操作,以免反复修改?这将如何改变路由的处理方式(我正在使用RESTful架构)?
我不是 RoR 专家,但找到了一个可能的方法。从参考网站中,您可以在config/initializers/inflections.rb
文件中添加变形规则:
# Add new inflection rules using the following format
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'clothing', 'clothes'
end
ActiveSupport::Inflector.inflections do |inflect|
,如果它找不到Inflector。 - Abe PetrilloActiveSupport::Inflector.inflections(:en)
- Sree Raj对于Rails 2.3.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