How do I override rails naming conventions?

别说谁变了你拦得住时间么 提交于 2019-12-24 04:45:16

问题


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".

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)?


回答1:


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.rb file:

# Add new inflection rules using the following format 
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'clothing', 'clothes'
end



回答2:


For rails 2.3.2 and maybe 2+, you need to do it a little different:

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



回答3:


Add this in your environment.rb file if you are trying to stop database pluralization

ActiveRecord::Base.pluralize_table_names = false



回答4:


With Ruby 2.2.2 windows or linux for me best solve was :

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


来源:https://stackoverflow.com/questions/14673532/rails-cant-map-automatically-y-ending-plural-models-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!