This is a little bit tricky, so if you need more information, don’t hesitate!
I have two models, Store and Consumer that are linked by two ways:
1/ Store and Consumer inherite from the same model Profile, because they share many attributes (name, location, email, web page,…). Here is the Rails AR code:
class Profile << ActiveRecord::Base
# Attributes and validation rules go here.
end
class Store << Profile
end
class Consumer << Profile
end
This is the well known Single Table Inheritance (STI).
2/ In addition to STI, Store and Consumer are linked by a many to many relation:
-
Store has many Clients (many consumers)
-
A consumer is client to many stores
Because I need more attributes for this link (Store – Consumer), I have to create an extra model that will link them: Client.
Here are my final AR models:
class Profile << ActiveRecord::Base
# Attributes and validation rules go here.
end
class Store << Profile
has_many :clients
end
class Consumer << Profile
has_many :clients
end
class Client << ActiveRecord::Base
belongs_to :store
belongs_to :consumer
end
Problem
Using STI doesn’t create store_id and consumer_id… we have only profile_id (because one real table Profile). So, how can I target the correct Client row having both store_id and client_id ?
Any idea how to do that? Thanks in advance.
I think you want to do is something like this. Also, I agree with Daniel Wright’s comment.
But if you’d like to make it work with what you have you could do something like: