I have the following model structure setup.
class User < ActiveRecord::Base
end
class Parent < User
has_many :relationships
has_many :children,
:class_name => “Student”,
:through => :relationships,
:conditions => “related_as = ‘parent’”
end
class Student < User
has_many :relationships
has_many :parents,
:through => :relationships,
:conditions => “related_as = ‘child’”
end
class Relationship < ActiveRecord::Base
belongs_to :parent, :foreign_key => :user_id
belongs_to :student, :foreign_key => :user_id
end
class CreateRelationships < ActiveRecord::Migration
def self.up
create_table :relationships do |t|
t.integer :user_id, :null => false
t.integer :related_user_id, :null => false
t.string :status, :null => false
t.string :related_as, :limit => 100, :null => false #
e.g. ‘parent’ or ‘child’ or ‘friend’
t.timestamps
end
end
def self.down
drop_table :relationships
end
end
I am trying to use the Relationship model to store many different
kinds of relationships like parent/child, friend/friend, husband/wife
etc.
With the above setup when I go to console I get the following
c = Student.find(144)
=>c.parents
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column
‘relationships.student_id’ in ‘where clause’: SELECTusers
.* FROM
users
INNER JOINrelationships
ONusers
.id =relationships
.user_id WHERE
((relationships
.student_id = 144) AND ((related_as = ‘child’))) AND
( (users
.type
= ‘Parent’ ) )
The problem is in WHERE clause relationships
.student_id - I don’t
have a student_id in that model (trying to keep it generic) and
instead want to use the related_user_id column from relationships
table. I have played around with the :foreign_key attribute on
belongs_to setup for relationships table and the way I have it setup
now generates the first part of the SQL correctly users
.id =
relationships
.user_id .
How do I change the relationships
.student_id to use
relationships
.related_user_id instead? Or is there a better/
different way to do what I am trying to accomplish? Do I have to
resort to a Polymorphic setup here (quick, half hearted try there
gives some other issues that I need to look deeper into if I have to
go down that route)?
I am on 2.3.8.
Thanks for your help.
-S