I want to be able to use two columns in one table to define relationships. Thus, using the task application as an example.
Attempt 1:
class User < ActiveRecord::Base has_many :tasks end class Task < ActiveRecord::Base belongs_to :owner, class_name: "User", foreign_key: "owner_id" belongs_to :assignee, class_name: "User", foreign_key: "assignee_id" end
So then Task.create(owner_id:1, assignee_id: 2)
This allows me to execute Task.first.owner , which returns user one and Task.first.assignee , which returns user two, but User.first.task does not return anything. This is due to the fact that the task does not belong to the user, they belong to the owner and assignee. In this way,
Attempt 2:
class User < ActiveRecord::Base has_many :tasks, foreign_key: [:owner_id, :assignee_id] end class Task < ActiveRecord::Base belongs_to :user end
It just crashes because two foreign keys are not supported.
Therefore, I want to say User.tasks and get both user-owned and assigned tasks.
In principle, somehow build a relationship that will be equal to the query Task.where(owner_id || assignee_id == 1)
Is it possible?
Update
I don't want to use finder_sql , but this unconfirmed answer seems close to what I want: Rails - Association with multiple indexes
Thus, this method will look like this:
Attempt 3:
class Task < ActiveRecord::Base def self.by_person(person) where("assignee_id => :person_id OR owner_id => :person_id", :person_id => person.id end end class Person < ActiveRecord::Base def tasks Task.by_person(self) end end
Although I can get it working in Rails 4 , I keep getting the following error:
ActiveRecord::PreparedStatementInvalid: missing value for :owner_id in :donor_id => :person_id OR assignee_id => :person_id