I have two classes that I would like to specify as follows:
class Club < ActiveRecord::Base
belongs_to :president, :class_name => "Person", :foreign_key => "president_id"
belongs_to :vice_president,
:class_name => "Person",
:foreign_key => "vice_president_id"
end
class Person < ActiveRecord::Base
has_one :club, :conditions =>
['president_id = ? OR vice_president_id = ?', '#{self.id}', '#{self.id}']
end
This doesn’t work and gives me an error when trying to get the club association from the person object. The error is because is looking for person_id in the club table when I looked at the SQL. I can get around it by declaring multiple has_one associations, but feel like this is the improper way of doing it.
A person can only be the President or Vice President of one club.
Anyone able to offer a little bit of advice on this issue, I would be very appreciative.
Your
has_onecondition will never work in Rails, as far as I know.You need one explicit
has_oneorbelongs_toor has_many per “link”, on both tables. So if you have two “links”, you need twohas_oneand twobelongs_to. That is how it works.Secondly, I think you should reconsider your models. The way you are doing it, one person can not be the president of a club and an employee, at the same time. Or be the president of two clubs. Even if you don’t have these right now, they can come in the future – it is easier to stay flexible right now.
A flexible way of doing this is using a
has_many :throughwith an intermediate table that specifies the role. In other words:Now, assuming that role_id=0 means employee, role_id=1 means president, and role_id=2 means vice_president, you can use it like this:
Additional notes:
have_manyrelationships and memberships wouldbelong_torole. Or, you could define methods in memberships for getting the role name (if 0, it returns “employee”, if 1, “president”, etc