Best practices to handle routes for STI subclasses in rails

后端 未结 18 1267
面向向阳花
面向向阳花 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 16:55

    If I consider an STI inheritance like this:

    class AModel < ActiveRecord::Base ; end
    class BModel < AModel ; end
    class CModel < AModel ; end
    class DModel < AModel ; end
    class EModel < AModel ; end
    

    in 'app/models/a_model.rb' I add:

    module ManagedAtAModelLevel
      def model_name
        AModel.model_name
      end
    end
    

    And then in the AModel class:

    class AModel < ActiveRecord::Base
      def self.instanciate_STI
        managed_deps = { 
          :b_model => true,
          :c_model => true,
          :d_model => true,
          :e_model => true
        }
        managed_deps.each do |dep, managed|
          require_dependency dep.to_s
          klass = dep.to_s.camelize.constantize
          # Inject behavior to be managed at AModel level for classes I chose
          klass.send(:extend, ManagedAtAModelLevel) if managed
        end
      end
    
      instanciate_STI
    end
    

    Therefore I can even easily choose which model I want to use the default one, and this without even touching the sub class definition. Very dry.

提交回复
热议问题