Ruby on Rails: How to create a dashboard for a pluralized model with the Administrate gem
Even when your model’s name is pluralized the administrate gem tries to singularize it, but here is a solution using inflections.
How I got the error?
I was trying to create a dashboard with the administrate gem for my model PaymentDetails, that I generated with this command:
1
rails generate model --force-plural PaymentDetails
My relations:
1
2
3
4
5
6
7
class User < ApplicationRecord
has_one :payment_details
end
class PaymentDetails < ApplicationRecord
belongs_to :user
end
Where does the error come from?
When I tried to make a dashboard for my model (there are other tutorials on the internet for that) I got the error that “PaymentDetail” is not found.
This is because the gem singularizes the model names and works from there.
I read a bit about such issues with namespace singularization errors(#1037 and #1931), but couldn’t get it to work.
The solution
1
2
3
4
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.uncountable 'PaymentDetails'
inflect.uncountable 'payment_details'
end
How it works
In Rails, an inflection is a transformation applied to words to convert them between singular and plural forms, among other modifications.
The ActiveSupport::Inflector provides methods to handle these transformations, ensuring that Rails can accurately interpret and generate word forms used in model names, table names, and other contexts. By configuring custom inflections, we can control how Rails handles words that do not follow standard English pluralization rules.
Our configuration specifies that “PaymentDetails” and “payment_details” should be treated as uncountable nouns. This means Rails will not attempt to pluralize or singularize these terms, preserving their form in all contexts.
Custom inflections are crucial for handling model names that are inherently plural or have specific naming conventions, ensuring consistency and avoiding errors in the application.
How to prevent this issue
Just be careful with the names of your models. Here PaymentDetails
made sense, because it stores payment details of the user. But Rails tries to singularize it as PaymentDetail
everywhere, so it becomes a hasle, even if we --force-plural
it. Just naming the model something as simple as PaymentInfo
would have saved us the trouble.