Skip to content

Instantly share code, notes, and snippets.

@senny
Last active December 17, 2015 13:49
Show Gist options
  • Save senny/5619555 to your computer and use it in GitHub Desktop.
Save senny/5619555 to your computer and use it in GitHub Desktop.
require 'logger'
require 'active_record'
ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: ":memory:"
)
ActiveRecord::Schema.define do
create_table :states do |table|
table.column :name, :string
table.column :code, :string
end
add_index :states, :code
create_table :cities do |table|
table.column :name, :string
table.column :state_code, :string
end
add_index :cities, :state_code
end
class State < ActiveRecord::Base
has_many :cities, foreign_key: :state_code
end
class City < ActiveRecord::Base
belongs_to :state, foreign_key: :state_code, primary_key: :code
end
state = State.create!(name: "A", code: "A")
state.cities.create!(name: "1")
state.cities.create!(name: "2")
new_city = City.create!(name: "3")
begin
state.cities = [new_city]
rescue => e
puts '===', e.message, '===', ''
end
state.save!
state.reload
p state.cities
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment