Skip to content

Instantly share code, notes, and snippets.

@harshalbhakta
Last active June 22, 2019 07:06
Show Gist options
  • Save harshalbhakta/e7051b3b865eeac8471b405fe7ba2091 to your computer and use it in GitHub Desktop.
Save harshalbhakta/e7051b3b865eeac8471b405fe7ba2091 to your computer and use it in GitHub Desktop.
Shop & Order example Rails script
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :shops, force: true do |t|
t.string :name, index: true
t.timestamps
end
create_table :orders, force: true do |t|
t.integer :supplier_id, index: true
t.integer :customer_id, index: true
t.decimal :order_total, default: 0.0
t.timestamps
end
end
class Shop < ActiveRecord::Base
has_many :supplier_orders, class_name: 'Order', foreign_key: 'supplier_id'
has_many :customer_orders, class_name: 'Order', foreign_key: 'customer_id'
end
class Order < ActiveRecord::Base
belongs_to :supplier, class_name: 'Shop', foreign_key: 'supplier_id'
belongs_to :customer, class_name: 'Shop', foreign_key: 'customer_id'
end
class ShopOrderTest < Minitest::Test
def test_sample_data
shop_1 = Shop.create! name: "Shop 1"
shop_2 = Shop.create! name: "Shop 2"
shop_3 = Shop.create! name: "Shop 3"
order_1 = Order.create! supplier: shop_1, customer: shop_2, order_total: 200
order_2 = Order.create! supplier: shop_1, customer: shop_3, order_total: 300
order_3 = Order.create! supplier: shop_3, customer: shop_2, order_total: 100
assert_equal order_1.id, shop_1.supplier_orders.first.id
assert_equal order_3.id, shop_2.customer_orders.second.id
assert_equal 2, shop_1.supplier_orders.count
assert_equal 2, shop_2.customer_orders.count
assert_equal 1, shop_3.supplier_orders.count
assert_equal 1, shop_3.customer_orders.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment