How to customize Rails 3 STI column name

后端 未结 4 1874
旧巷少年郎
旧巷少年郎 2020-12-31 11:08

I have a class named Post:

class Post < ActiveRecord::Base
end

I have a class named Question that inheriting f

相关标签:
4条回答
  • 2020-12-31 11:11

    You can change the name of the single table inheritance column like so:

    class Post < ActiveRecord::Base
      self.inheritance_column = 'type_column_name'
    
    end
    

    However, there is no way to cause Rails to use integers instead of storing the actual type as a string, which makes me think that this may not be a great use case for single target inheritance. Perhaps a scope would suit you better instead:

    class Post < ActiveRecord::Base
      scope :questions, where(:post_type_id => 0)
      scope :answers, where(:post_type_id => 1)
    
    end
    
    @questions = Post.questions.all
    @answers = Post.answers.all
    
    0 讨论(0)
  • 2020-12-31 11:16

    This might be what you're looking for.

    http://lorefnon.me/2014/07/27/optimizing-sti-columns.html

    EDIT: Updated URL (thanks @SubhashChandran)

    0 讨论(0)
  • 2020-12-31 11:22

    There actually is a way, as with all things. You can override the find_sti_class method to look for your type based on an integer.

    0 讨论(0)
  • 2020-12-31 11:29

    You will need to set your column type using self.inheritance_column Then you will have to provide your own behavior for the following method: "sti_class_for(type_name)" which is located in this file "activerecord/lib/active_record/inheritance.rb"

    so you will have to monkey patch the above file.

    This is not the recommended way, you will have to make a migration and change all the values to match your class name.

    0 讨论(0)
提交回复
热议问题