Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kamui/3146430 to your computer and use it in GitHub Desktop.
Save kamui/3146430 to your computer and use it in GitHub Desktop.
nested_attributes and many_to_one relationship validation
require 'sequel'
require 'sqlite3'
require 'logger'
DB = Sequel.sqlite
# DB.loggers << Logger.new($stdout)
Sequel::Model.plugin :validation_helpers
Sequel::Model.raise_on_save_failure = false
DB.instance_eval do
create_table :orders do
primary_key :id
Integer :quantity
Integer :price_in_cents
foreign_key :shopper_id, :shoppers
end
create_table :shoppers do
primary_key :id
String :email
end
end
class Order < Sequel::Model
many_to_one :shopper
plugin :nested_attributes
nested_attributes :shopper
def validate
super
validates_presence [:quantity, :price_in_cents]
end
end
class Shopper < Sequel::Model
one_to_many :orders
def validate
super
validates_presence :email
end
end
o = Order.new(quantity: 1, price_in_cents: 100_00, shopper_attributes:
{ email: '[email protected]' })
o.save
o2 = Order.new(quantity: 1, price_in_cents: 100_00)
o2.save
puts o2.errors
o3 = Order.new
o3.save
puts o3.errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment