12

I have a class named Post:

class Post < ActiveRecord::Base
end

I have a class named Question that inheriting from Post:

class Question < Post
end

and I have a class named Answer that also inheriting from 'Post':

class Answer < Post
end

In Post, I have a column named post_type_id and its' type is Integer.
How do I use STI and specific column name & type to inherit from Post? 0 means Question and 1 means Answer. (0 & 1 is the value of post_type_id in posts table)

VvDPzZ
  • 2,995
  • 1
  • 23
  • 28

4 Answers4

25

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
Veraticus
  • 15,944
  • 3
  • 41
  • 45
10

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.

Finbarr
  • 31,350
  • 13
  • 63
  • 94
3

This might be what you're looking for.

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

EDIT: Updated URL (thanks @SubhashChandran)

Volte
  • 1,905
  • 18
  • 25
0

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.

Rudy Zidan
  • 101
  • 4