Attributes on an Association

59 views
Skip to first unread message

Neil Chaudhuri

unread,
Apr 21, 2012, 1:30:57 AM4/21/12
to DataMapper
I need to store people, albums, photos, and the order that photos
appear in an album, so I decided to try adding a "position" attribute
to the association between Photo and Album. Consider the following
models:

class Person
include DataMapper::Resource
...
end

class Album
include DataMapper::Resource
...
has n, :photos, "Photo", :through => :album_photos, :via => :photo
end

class Photo
include DataMapper::Resource
...

belongs_to :person, :required => true
has n, :albums, "Album", :through => :album_photos, :via => :album
end

class AlbumPhoto
include DataMapper::Resource

property :position, Integer, :default => 1

belongs_to :album, :key => true
belongs_to :photo, :key => true

end

First, is such the right way to achieve this sort of thing? I didn't
see anything like this in the documentation.

To add a wrinkle, I have a model called Book which has a 1:M
relationship with Album. When I execute the following code

album.album_photos.destroy
album.album_photos << AlbumPhoto.new({:position =>3})
book.update

I get "DataMapper::UpdateConflictError: Book#update cannot be called
on a dirty resource"

I am curious if my models are defined correctly. If so, how can I
delete all prior associations and update their positions "cleanly"?

Thanks.


Neil Chaudhuri

unread,
Apr 21, 2012, 1:07:01 PM4/21/12
to datam...@googlegroups.com
I tried a different and actually a lot more sensible approach as follows:

my_hash.each do |id, some_string_that_is_irrelevant|
      album_photo = album.album_photos.first(:photo_id=>id)  #Didn't want to reach to the database for an actual Photo instance
      album_photo.position = position
      position += 1
end

However, I still get DataMapper::UpdateConflictError: Book#update cannot be called on a dirty resource

This really boggles my mind because all I am doing is updating a single non-PK attribute through the API.

If anyone sees something I am missing, I would appreciate the help.

Thanks.
Reply all
Reply to author
Forward
0 new messages