Guest User

Untitled

a guest
Nov 19th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. require 'sequel'
  2. require 'sqlite3'
  3. require 'logger'
  4. require 'pry'
  5.  
  6. DB = Sequel.sqlite
  7. DB.loggers << Logger.new($stdout)
  8.  
  9. Sequel::Model.plugin :validation_helpers
  10.  
  11. DB.instance_eval do
  12. create_table :products do
  13. primary_key :id
  14. String :name
  15. String :description
  16. end
  17.  
  18. create_table :variants do
  19. primary_key :id
  20. String :name
  21. foreign_key :product_id, :products
  22. end
  23. end
  24.  
  25. class Product < Sequel::Model
  26. one_to_many :variants
  27.  
  28. plugin :nested_attributes
  29. nested_attributes :variants
  30.  
  31. def variants_attributes=(variants)
  32. super
  33. associations[:variants].each{|v| v.skip_product_validation = true}
  34. end
  35. end
  36.  
  37. class Variant < Sequel::Model
  38. many_to_one :product
  39.  
  40. attr_accessor :skip_product_validation
  41.  
  42. def validate
  43. super
  44. validates_presence :product unless skip_product_validation
  45. end
  46. end
  47.  
  48. p = Product.new(name: 'bar', variants_attributes: [{ name: 'foo' }])
  49. p.save
  50.  
  51. v = Variant.new(name: 'variant')
  52. v.save
  53.  
  54. # binding.pry
Add Comment
Please, Sign In to add comment