Using Rails Inflections with `rails generate`

2019-07-22 01:22发布

问题:

I'm trying to generate a model called ClassAttendance, but Rails keeps naming the migrations class_attendances. I've tried correcting this problem by placing the following code the following code in \config\initializers\inflections.rb:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.uncountable "attendance"
end

This seems to work fine in the rails console:

$ rails console
Loading development environment (Rails 3.2.6)
irb(main):001:0> "attendance".pluralize
=> "attendance"

Unfortunately, the rails model generator seems to be unaffected:

$ rails generate model ClassAttendance 
      invoke  active_record
      create    db/migrate/20120806201910_create_class_attendances.rb
      create    app/models/class_attendance.rb
      invoke    rspec
      create      spec/models/class_attendance_spec.rb

Does it have something to do with this?

irb(main):002:0> "class_attendance".pluralize
=> "class_attendances"

Or is there some other problem I'm not seeing?

回答1:

That is the workaround, you need to place it in the inflections.rb file in the config/initializers/. So your config/initializers/inflections.rb would be

ActiveSupport::Inflector.inflections do |inflect| 
  inflect.uncountable %w( attendance class_attendance ClassAttendance) 
end