Many to Many problem

5 views
Skip to first unread message

Charlotte

unread,
Feb 1, 2009, 11:32:12 AM2/1/09
to DataMapper
Hello Everyone,

I was having some problems with many to many relationships. To make
things simpler, I tried the examples from the datamapper website
(http://datamapper.org/doku.php?id=docs:associations), modifying the
code a little bit:

class Photo
include DataMapper::Resource

property :photo_id, Serial
property :name, String

has n, :taggings
has n, :tags, :through => :taggings, :mutable => true
end

class Tag
include DataMapper::Resource

property :tag_id, Serial
property :name, String

has n, :taggings
has n, :photos, :through => :taggings, :mutable => true

end

class Tagging
include DataMapper::Resource

property :tagging_id, Serial

belongs_to :tag
belongs_to :photo
end

When I try to do the following in irb:

p = Photo.new(:name => 'First Photo')
=> #<Photo photo_id=nil name="First Photo">
irb(main):002:0> p.save
=> true
irb(main):003:0> t = Tag.new(:name => 'cool')
=> #<Tag tag_id=nil name="cool">
irb(main):004:0> t.save
=> true
irb(main):005:0> p.tags << t
=> [#<Tag tag_id=1 name="cool">]
irb(main):006:0> p.save

After the last line, I get the following error:
undefined method `attach_parent' for
#<DataMapper::Associations::RelationshipChain:0xb73274d8>

Is this a bug or am I doing something wrong? I'm using MySQL and my
DataMapper version is 0.9.10.

Thanks for the help guys!

asartalo

unread,
Feb 4, 2009, 1:42:30 PM2/4/09
to DataMapper
I had the same problem with my project. After scouring the internet, I
found this blog post on a possible solution:

http://brilliantcorners.org/nodes/146-getting-has-many-through-working-with-datamapper

It looks like this is a known bug and the developers are probably
working on this:
http://datamapper.lighthouseapp.com/projects/20609/tickets/725-bug-with-many-to-many-association

That said, I created a workaround for my project and it hasn't given
me any problems yet. It probably isn't the best solution out there
('cause I'm a newbie, you see). For one, it doesn't check for
duplicates when you're adding tags. If anyone has a better
alternative, please post them here. I'm also interested in what others
have to say.

The code below is for the Photo model but you can do the same for the
Tag.

class Photo
include DataMapper::Resource

property :photo_id, Serial
property :name, String

has n, :taggings

def tags
@tags || @tags = taggings.tag
end

before :save do
tags unless @tags
ts = taggings.tag
# remove the taggings we don't want
ts.each do |t|
t.destroy unless t.in? @tags
end
# create new tags we do want
@tags.each do |t|
taggings.new(:tag_tag_id => t.tag_id) unless t.in? ts
end
end

end


Hope this helps!
Reply all
Reply to author
Forward
0 new messages