Two many "has many" makes queries fail on the first time (and first time only)

9 views
Skip to first unread message

Daniel Ribeiro

unread,
Jul 19, 2011, 2:55:15 PM7/19/11
to datam...@googlegroups.com
Hi,:

I've had this problem for a while, but recently set it up on github: https://github.com/danielribeiro/Datamapper-Has-Many-Bug-report :

model : defines the model
class Video
  include DataMapper::Resource
  property :id, DataMapper::Property::Serial
  property :name, String
  has n, :play_list_assocs
  has n, :lists, "PlayList", :through => :play_list_assocs, :via => :play_list
  belongs_to :user
end

class PlayList
  include DataMapper::Resource
  property :id, DataMapper::Property::Serial
  property :name, String
  has n, :play_list_assocs
  has n, :videos, "Video", :through => :play_list_assocs, :via => :video
  belongs_to :user
end

class PlayListAssoc
  include DataMapper::Resource
  property :id, DataMapper::Property::Serial
  property :position, Integer
  belongs_to :video, :key => true
  belongs_to :play_list, :key => true
end

class User
  include DataMapper::Resource
  property :id, DataMapper::Property::Serial
  has n, :play_lists
  has n, :videos
  property :name, String
end


filldb : generates de sqlite db (it is commited on the project). It sets :

u = User.create :name => 'username'
g = Video.create :name => 'video name', :user => u
g.lists << PlayList.create(:user => u, :name => 'list name name')

tryread :  tries to read all the videos from all the playlists of the user:
for g in Video.all
  f = g.play_list_assocs.first
  p f.play_list if f
end

for g in Video.all
  f = g.play_list_assocs.first
  p f.play_list if f
end

The result?
nil
#<PlayList @id=1 @name="list name name">

So it seems that the play_list_assoc -> play_list association is only read after the database is used for the first time. On production I have to force this first use in order to avoid this erroneus behaviour.

Any ideas?

Jonathan Stott

unread,
Jul 19, 2011, 3:22:59 PM7/19/11
to datam...@googlegroups.com
Hi

You should call 'DataMapper.finalize' before using your models but
after requiring them all. This does a basic sanity check, sets up all
the associations and other things that can only be done when all the
models are loaded up.

Regards
Jon

> --
> You received this message because you are subscribed to the Google Groups
> "DataMapper" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/datamapper/-/ARc8RrWPYBcJ.
> To post to this group, send email to datam...@googlegroups.com.
> To unsubscribe from this group, send email to
> datamapper+...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/datamapper?hl=en.
>

Daniel Ribeiro

unread,
Jul 19, 2011, 3:25:28 PM7/19/11
to datam...@googlegroups.com
Thanks a lot! it solved it! I'll push the version with bug fixxed.
Reply all
Reply to author
Forward
0 new messages