Skip to content

Instantly share code, notes, and snippets.

@kamui
Created June 28, 2012 23:57
Show Gist options
  • Save kamui/3014816 to your computer and use it in GitHub Desktop.
Save kamui/3014816 to your computer and use it in GitHub Desktop.
nested_attributes in a one_to_many relationship with a presence validation on the parent model
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment