I’ve been playing around with STI in rails and had a question about associating records with a specific model.
Say I have a Product model with the following schema:
# id :integer not null, primary key
# url_name :string(255) not null
# cover_img :string(255)
# created_at :datetime not null
# updated_at :datetime not null
From this Product model, I create 2 inherited models:
Foo:
class Foo < Product
end
Bar:
class Bar < Product
end
Say I save a record to Foo(A), and a record to Bar(B). When I call Product.all, I expect to get all records A and B. However when i call Foo.all or Bar.all I expect to only retrieve A and B respectively, but what happening is that when I call either Foo.all or Bar.all, I get the result I get when call Product.all. How to I configure this relationship to get the expected results?
I am using rails 3.2.6 and Ruby 1.9.3
You need to add a ‘type’ column to your products table so that ActiveRecord can distinguish between instances of the different types. This column should have a string type, like: