My Rails views and controllers are littered with redirect_to
, link_to
, and form_for
method calls. Sometimes link_to
and <
The cleanest solution I found is to add the following to the base class:
def self.inherited(subclass)
super
def subclass.model_name
super.tap do |name|
route_key = base_class.name.underscore
name.instance_variable_set(:@singular_route_key, route_key)
name.instance_variable_set(:@route_key, route_key.pluralize)
end
end
end
It works for all subclasses and is much safer than overriding the entire model name object. By targeting only the route keys, we solve the routing problems without breaking I18n or risking any potential side effects caused by overriding the model name as defined by Rails.