Forum: Ruby on Rails How to handle cardinality 1-to-2 with Associations ?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Simon (Guest)
on 2007-06-29 19:52
(Received via mailing list)

I am new to RoR and am coding a small budgetting app with two tables
(see below). As you can see every account has_many transactions and
every transaction has 2 accounts. How can I best respresent this using
ActiveRecord::Associations ?

create table accounts (
  id                     int not null auto_increment,
  name                varchar(100)   not null default '',
  primary key(id)

create table transactions (
    id                     int                  not null
    month             varchar(3)       not null,
    amount             int                  null,
    from_id             int                  not null,
    to_id                int                  not null,
    constraint fk_from_accounts foreign key (from_id) references
    constraint fk_to_accounts foreign key (to_id) references
    primary key(id)
) engine=InnoDB;

I see 3 possible solutions but nothing elegant:
- create 2 relationship tables (from and to)
- use sql
- code belongs_to_2 association

I would very much like your advice on this.

Thanks !
Steve T. (Guest)
on 2007-06-29 20:12
(Received via mailing list)
Hi Simon,

I think you need to model two relationships.

class Transaction < AR::Base
  belongs_to :creditor, :class_name => 'Account', :foreign_key =>
'creditor_id'  #from_id
  belongs_to :debitor, :class_name => 'Account', :foreign_key =>
'debitor_id'   #to_id

class Account < AR:Base
  has_many :credits, :class_name => 'Transaction', :foreign_key =>
'creditor_id'   #from_id
  has_many :debits, : class_name => 'Transaction', :foreign_key =>
'debitor_id'   #to_id

Michael L. (Guest)
on 2007-06-29 22:21
(Received via mailing list)
That certainly works.  You can also put in a validation for the
transaction and the account classes to limit the number of
associations between them if you want to treat all associations

Simon (Guest)
on 2007-06-30 10:27
(Received via mailing list)
Thanks you Steve, that is exactly what I was looking for. (I got so
close but couldn't figure it out :-) ).

This topic is locked and can not be replied to.