Reputation: 2795
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
Upvotes: 0
Views: 340
Reputation: 718
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:
create_table :products do |t|
# your other columns
t.string :type
end
Upvotes: 2
Reputation: 27124
The answer lies in how you are saving the object. You're probably saving them as either a Foo or a Bar, and not as a Product as you should be. When I use inherited models like you are, I'm generally only doing so to inherit communal ways to identify their datas.
So I would have for example, a Question, and two different types of questions like a Grammar and a Visual that would both inherit Question. But I would be saving the Object as question in the QuestionsController.
Just like you should be saving your objects with the ProductsController.
Upvotes: 0