Created
April 16, 2012 20:04
-
-
Save jamiehodge/2401139 to your computer and use it in GitHub Desktop.
Nested Attributes example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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