Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@will
Created October 31, 2008 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save will/21256 to your computer and use it in GitHub Desktop.
Save will/21256 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# datamapper woes
# Case one: adding an object to an association using << blows up
# Case two: setting an association with a new array doesn't clear
# out the old one, it just combines them
# output:
# line 49: post.tags << t1 # => #<DataMapper::Associations::ImmutableAssociationError: You can not modify this association>
# line 74: book.authors == [ a1 ] # => true
# line 79: book.authors == [ a2 ] # => false
# line 80: book.authors # => [#<Author id=1>, #<Author id=2>]
require 'rubygems'
require 'dm-core' # on both 0.9.6 and 0.9.7[ba7a38]
class Tagging
include DataMapper::Resource
property :id, Serial
belongs_to :post
belongs_to :tag
end
class Post
include DataMapper::Resource
property :id, Serial
has n, :taggings
has n, :tags, :through => :taggings
end
class Tag
include DataMapper::Resource
property :id, Serial
has n, :taggings
has n, :posts, :through => :taggings
end
# DataMapper::Logger.new(STDERR, :debug)
DataMapper.setup(:default, 'sqlite3::memory:')
DataMapper.auto_migrate!
post = Post.create
t1 = Tag.create
t2 = Tag.create
begin
post.tags << t1
rescue => e
puts "line #{__LINE__}: post.tags << t1 # => #{e.inspect}"
end
class Book
include DataMapper::Resource
property :id, Serial
has n, :authors, :through => Resource
end
class Author
include DataMapper::Resource
property :id, Serial
has n, :books, :through => Resource
end
DataMapper.auto_migrate!
book = Book.create
a1 = Author.create
a2 = Author.create
book.authors << a1
book.save
book.reload
puts "line #{__LINE__}: book.authors == [ a1 ] # => #{book.authors == [ a1 ]}"
book.authors = [ a2 ]
book.save
book.reload
puts "line #{__LINE__}: book.authors == [ a2 ] # => #{book.authors == [ a2 ]}"
puts "line #{__LINE__}: book.authors # => #{book.authors.inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment