问题
I want to create a model in rails:
rails generate model ABCThing
So this will create a table, abc_things. Great. The problem comes with the controller and routing. I want my controller to be:
class ABCThingsController < ApplicationController
end
However, after adding in the routes.rb
resources :abc_things, :only => [:index]
and creating the corresponding index view, i get the following error in the browser:
Expected /app/controllers/abc_things_controller.rb to define AbcThingsController
The problem is easy to see ("ABCThings".tableize.classify => "AbcThing"), but i'm not so sure how to fix it. I want to override rails default routing from the view to the controller, but am not sure how.
Would appreciate any help (and suggestions for a better question title!)
回答1:
I had this issue and after trying all of the above solutions; was able to fix my problem using the inflector.
In my case the issue was that TLA::ThingsController was being resolved as Tla::ThingsController
putting the following in my initializers folder fixed it
config/initializers/inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
inflect.acronym 'TLA'
end
回答2:
You should set custom controller name, in routes.rb:
resources :abc_things, :only => [:index], :controller => "ABCThings"
回答3:
This may have changed with Ruby at some point, but for naming classes with multiple caps in a row (acronyms or initialisms), you no longer need to include the underscore in the file name.
# abc_thing.rb
could contain
class ABCThing
def hello
puts "Hello World"
end
end
or
class AbcThing
def hello
puts "Hello World"
end
end
回答4:
When you run command
rails generate model ABCThings
It will generate model and not a controller. If you want both model and controller use following
rails generate scaffold ABCThings
I think you are not generate controller by using rails command and hence problem was occured to generate controller use following command
rails generate controller ABCThings
and you can /app/controllers/abc_things_controller.rb as follows
class AbcThingsController < ApplicationController
end
来源:https://stackoverflow.com/questions/12509176/override-rails-controller-routing-with-capital-letters-in-model-name