How to handle cardinality 1-to-2 with Associations?

Hello,

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
auto_increment,
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
accounts(id),
constraint fk_to_accounts foreign key (to_id) references
accounts(id),
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 !
Simon

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
uniformly.

Michael

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
end

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
end

Steve

Thanks you Steve, that is exactly what I was looking for. (I got so
close but couldn’t figure it out :slight_smile: ).

Simon

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs