Here is a quick question, I have 2 models as follows, when I create a new instance of Question model, its post_type attr is nil.
But when I try that with rails c, I can see that it get value 1, and when I save the model, its value is still nil.
Any explanation?
class Post < ActiveRecord::Base
POST_QUESTION = 1
end
class Question < Post
def initialize
p "post_type=#{@post_type}"
@post_type = Post::POST_QUESTION
super
p "post_type=#{@post_type}"
end
end
Rails will handle things like this for you with Single Table Inheritance. You need a
"type"string column in thepoststable.Any question you create will be saved to the posts table with type
"Question".Is there a reason you need the post types to be integers?
Anyway, the reason it’s not working as you’ve written it is that all of the model attributes are stored in an instance variable called
@attributes. While you can use other instance variables once the object is loaded from the database, ActiveRecord won’t pay any attention to them.