STI, one controller

后端 未结 5 2022
谎友^
谎友^ 2020-11-27 09:49

I\'m new to rails and I\'m kind of stuck with this design problem, that might be easy to solve, but I don\'t get anywhere: I have two different kinds of advertisements: high

5条回答
  •  一整个雨季
    2020-11-27 10:40

    fl00r has a good solution, however I would make one adjustment.

    This may or may not be required in your case. It depends on what behavior is changing in your STI models, especially validations & lifecycle hooks.

    Add a private method to your controller to convert your type param to the actual class constant you want to use:

    def ad_type
      params[:type].constantize
    end
    

    The above is insecure, however. Add a whitelist of types:

    def ad_types
      [MyType, MyType2]
    end
    
    def ad_type
      params[:type].constantize if params[:type].in? ad_types
    end
    

    More on the rails constantize method here: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-constantize

    Then in the controller actions you can do:

    def new
      ad_type.new
    end
    
    def create
      ad_type.new(params)
      # ...
    end
    
    def index
      ad_type.all
    end
    

    And now you are using the actual class with the correct behavior instead of the parent class with the attribute type set.

提交回复
热议问题