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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B1388d8f0fbf3060df044f3fd5b620f5?d=identicon&s=25 Simon (Guest)
on 2007-06-29 17:52
(Received via mailing list)
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
Ee7052b87b82257740f232a958c3d49e?d=identicon&s=25 Steve Tooke (Guest)
on 2007-06-29 18: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
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
588ab1c0a5610a7e160a3b101abb91e6?d=identicon&s=25 Michael Latta (Guest)
on 2007-06-29 20: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
uniformly.

Michael
B1388d8f0fbf3060df044f3fd5b620f5?d=identicon&s=25 Simon (Guest)
on 2007-06-30 08: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 :-) ).

Simon
This topic is locked and can not be replied to.