Best practices to handle routes for STI subclasses in rails

后端 未结 18 1263
面向向阳花
面向向阳花 2020-11-30 16:25

My Rails views and controllers are littered with redirect_to, link_to, and form_for method calls. Sometimes link_to and <

18条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 17:07

    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.

提交回复
热议问题