Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Created April 16, 2012 20:04
Show Gist options
  • Select an option

  • Save jamiehodge/2401139 to your computer and use it in GitHub Desktop.

Select an option

Save jamiehodge/2401139 to your computer and use it in GitHub Desktop.
Nested Attributes example
require 'sequel'
require 'sqlite3'
DB = Sequel.sqlite
DB.instance_eval do
create_table :artists do
primary_key :id
String :name
end
create_table :albums do
primary_key :id
foreign_key :artist_id
String :name
end
end
class Artist < Sequel::Model
one_to_many :albums
plugin :nested_attributes
nested_attributes :albums, destroy: true
end
class Album < Sequel::Model
many_to_one :album
end
a = Artist.new name: 'YJM'
a.albums_attributes = [ { name: 'RF' }, { name: 'MO' } ]
a.save
a.update albums_attributes: [ { id: 1, name: 'T' } ]
a.update albums_attributes: [ { id: 1, _delete: true } ]
a.albums # => [#<Album @values={:id=>1, :artist_id=>1, :name=>"T"}>, #<Album @values={:id=>2, :artist_id=>1, :name=>"MO"}>]
a.refresh
a.albums # => [#<Album @values={:id=>2, :artist_id=>1, :name=>"MO"}>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment