Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'sequel'
- require 'sqlite3'
- require 'logger'
- require 'pry'
- DB = Sequel.sqlite
- DB.loggers << Logger.new($stdout)
- Sequel::Model.plugin :validation_helpers
- DB.instance_eval do
- create_table :products do
- primary_key :id
- String :name
- String :description
- end
- create_table :variants do
- primary_key :id
- String :name
- foreign_key :product_id, :products
- end
- end
- class Product < Sequel::Model
- one_to_many :variants
- plugin :nested_attributes
- nested_attributes :variants
- def variants_attributes=(variants)
- super
- associations[:variants].each{|v| v.skip_product_validation = true}
- end
- end
- class Variant < Sequel::Model
- many_to_one :product
- attr_accessor :skip_product_validation
- def validate
- super
- validates_presence :product unless skip_product_validation
- end
- end
- p = Product.new(name: 'bar', variants_attributes: [{ name: 'foo' }])
- p.save
- v = Variant.new(name: 'variant')
- v.save
- # binding.pry
Add Comment
Please, Sign In to add comment