ProblemI am creating a messaging system-like feature on one of my projects. My structure is something like this:
Account - id - [...other related columns about the account class..] Message - id - account_from - account_to - message - status - create_at - updated_at
Based on the structure,
Messagehas two foreign key (
account_to). Both of these are pointing to the Account model.
AnalysisTechnically, I would need a many-to-many relationship.
To solve this, we need to declare a couple of
belongs_tothat will be visible on the two models.
CodeFor the Account model:
class Account < ActiveRecord::Base has_many :account_froms, :class_name => "Message", :foreign_key => :account_from_id has_many :account_tos, :class_name => "Message", :foreign_key => :account_to_id .... end
And for the Message model:
class Message < ActiveRecord::Base belongs_to :account_from, :class_name => "Account", :foreign_key => :account_from_id belongs_to :account_to, :class_name => "Account", :foreign_key => :account_to_id .... end
With this, I can easily use
@account.account_tosto get all messages related to the said acocunt.