Say we want to model a transaction in rails between a buyer and seller which are represented as users in the system.

How do you model that in activerecord?

The short

Basically we use the user model for both the buyer and seller for manually specifying the id’s in the transaction table.

class Transaction < ActiveRecord::Base
  has_one :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  has_one :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

The long

Create the user

> rails g scaffold User name:string bank:string

Create the transaction

> rails g scaffold Transaction buyer_id:integer seller_id:integer amount:decimal
> rake db:migrate
> rails s

Update transaction to reflect buyer/seller user ids

class Transaction < ActiveRecord::Base
  has_one :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  has_one :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

user_model_two_abstractions

Write a test

test/models/transaction_test.rb

require 'test_helper'

class TransactionTest < ActiveSupport::TestCase
  test 'Create transaction' do
    buyer = User.new(name: 'Peter', bank: 'TD')
    seller = User.new(name: 'Paul', bank: 'Royal')

    tx = Transaction.new(buyer_id: buyer.id, seller_id: seller.id, amount: 100000.0)

    assert_equal(buyer.id, tx.buyer_id)
    assert_equal(seller.id, tx.seller_id)
    assert_equal(100000.0, tx.amount)
  end
end

Should now be able to use User for multiple abstractions – a buyer and a seller.

Advertisement