I have something like this my user model
class User < ActiveRecord::Base
has_many :received_msgs, class_name:"Message", foreign_key: "recipient_id", :conditions =>['owner_id = ?', self.id]
has_many :sent_msgs, class_name: "Message", foreign_key: "sender_id", :conditions =>['owner_id = ?', self.id]
where I want the owner_id to almost act as a secondary foreign key since each message is duplicated for independent deletion.
However, I’m getting an error saying id isn’t defined for the object. How do I access self.id in this case? Or is there a better way of doing this?
Thanks
Are you sure you don’t just want the
foreign_keyto beowner_id? That way, you won’t need thatconditionsarray at all.Anyhow, the reason you can’t access
self.idin the associations definition is because of what scope the code is evaluated in. The associations are evaluated when loading the class, and not when actually calling the#received_msgsmethod on aUserinstance.I believe you could access the
self.idof the instance by wrapping the conditions array in a lambda. That way it will not be evaluated until you call it.