Reputation: 869
If I have a legacy database where I the relationships between 2 entities are defined in a different table. How do I create that relationship in rails?
The basic relationship I want to present is:
---Admins:
First_name
Last_name
id
---Sites:
id
subject
---Admin_Sites
id
teacher_id
class_id
I know in rails I would just use belongs_to: and has_many: but if I have a (constantly updated) teach_class table, I need to somehow specify that THAT's where rails need to look for the relationship of who is related to which class. I am at a loss how I can specify this. Is it possible to somehow specify :foreign_key as "teach_class.teacher_id" in classes model?
Upvotes: 0
Views: 68
Reputation: 6036
see this blog for has_many :through relationship - http://ruby-on-rails-dipak-panchal.blogspot.in/2012/10/has-many-through-relationship.html
class Admin < ActiveRecord::Base
has_many :admin_sites
has_many :sites, :through => :admin_sites
end
class Site < ActiveRecord::Base
has_many :admin_sites
has_many :admins, :through => :admin_sites
end
class AdminSites < ActiveRecord::Base
belongs_to :admin
belongs_to :site
end
Upvotes: 0
Reputation: 531
In Teacher Model you would have
has_many :teach_classes
has_many :classes, :through => :teach_classes
Upvotes: 1