You should probably go for the following associations:
User:
has_many :notifications_as_notifier, :class_name=>'Notification', :foreign_key=>'notifier_id'
has_many :notifications_as_notifiee, :class_name=>'Notification', :foreign_key=>'notifiee_id'
Notification:
belongs_to :notifier, :class_name=>'User', :foreign_key=>'notifier_id'
belongs_to :notifiee, :class_name=>'User', :foreign_key=>'notifiee_id'
Your notifications
table should have notifier_id
and notifiee_id
.
Now you can do,
@notification = Notification.new
@notification.notifier = current_user
@notification.notifiee = User.first #Just for the sake of the example
@notification.save
What I find questionable in your setup:
You have,
has_one :notifier, :class_name => "User"
belongs_to :notifiee, :class_name => "User"
When you use has_on
, then the other relation (table) must have a foreign key referencing the parent. Here users
must have a column notification_id
or something. This is impractical because a single user has many notifications (based on your explanations).
Secondly, you are associating Notification to User through two relationships but you are mentioning anything about the foreign key to use to enforce the association.
And why do you not have an inverse relation in the User model? Would it not help if you had access to something like: current_user.notifications_as_notifier
??