salt.racer
salt.racer

Reputation: 22362

Rails, RESTful routing, and pluralization

I am struggling with the pluralization of the RESTful route generation in Rails 2.3.2.

Specifically, I have a resource called sitestatus. This resource really is uncountable (deer is deer, not deers). When I specify it as uncountable in an intializer, I get some helpers, but the sitestatuses_path is unavailable (which would make sense).

So, in a gesture to conformity, I have allowed sitestatus to be countable. So now, Rails pluralizes sitestatus to sitestatuses (not too horrible), but it insists on also singularizing it to sitestatu (missing the 's', hilarious and horrible at the same time).

So, I whipped out my bigger hammer and added this code to the intializer:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural "sitestatus", "sitestatuses"
  inflect.singular "sitestatus", "sitestatus"
end

(Note: I tried using irregular and it didn't work right)

Doing this gives me the expected results in the console when I "sitestatus".pluralize, but when I attempt to make a call to sitestatuses_path in my view I get

undefined local variable or method 'sitestatuses_path'

When I load up ActionController::UrlHelper in the console and call sitestatus_path(123) I get sitestatus/123 as I would expect. However, when I call sitestatuses_path I get

undefined method 'sitestatuses_path' for #<Object...

This name is the name of the model and the controller and it really is the only logical name for both as it lines up with the business name for the object perfectly.

What am I missing?

Upvotes: 2

Views: 1956

Answers (2)

Duncan Beevers
Duncan Beevers

Reputation: 1820

You can find out the named route method names for your routes and the urls for accesing them by invoking rake routes.

Upvotes: 1

salt.racer
salt.racer

Reputation: 22362

Okay, as it turns out I didn't need to use the inflector. Rails was already doing the right thing with respect to the word sitestatus.

There were a couple problems and a couple solutions that I needed to employ.

Problem 1: I was using map.resources :sitestatus, not map.resources :sitestatuses. The "s" at the end of the word was making Rails think that it was already pluralized as it should be. Thus the funny sitestatu_path helpers.

Solution: Pluralize :sitestatus to :sitestatuses.

This created two problems:

Problem A: Rails now assumed that the controller was named "Sitestatuses" which it is not. Solution A: Use the :controller hash_hey provided by the Rails router to rename the controller.

Problem B: Rails assumed that the url path that I wanted generated should be /sitestatuses, which it should not be. Solution B: Use the :as hash_key to rename the url generated.

Now, everything works perfectly.

Upvotes: 3

Related Questions