I have a database structure I am working with, where a Node
relates to one of two possible fields in the Interviewees
(either clientnode_id
OR caregivernode_id
):
tbl_nodes
+----+-----------+
| id | node_Name |
+----+-----------+
| 5 | some name |
+----+-----------+
tbl_interviewees
+----+---------------+------------------+
| id | clientnode_id | caregivernode_id |
+----+---------------+------------------+
| 1 | 5 | NULL |
+----+---------------+------------------+
I am simply trying to define a has_many
in the Node model where matches from either field are included. The equivalent SQL would be:
SELECT * FROM tbl_nodes LEFT JOIN tbl_interviewees ON (tbl_nodes.id=tbl_interviewees.clientnode_id OR tbl_nodes.id=tbl_interviewees.caregivernode_id)
I have currently attempted the advice on the following links to no avail (most use deprecated syntax):
Rails 3: Use of lambda with scopes in model
Rails has_many with dynamic conditions
http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference Rails has_many conditions
Probably just something fiddly with the syntax, so any help would be appreciated. I know this is wrong but this is my most recent attempt:
class Node < ActiveRecord::Base
self.table_name_prefix = :tbl_
has_many :interviewees, -> { where("clientnode_id=? OR caregivernode_id=?", self.id, self.id) }
end