开发者

Maintaining DataMapper Ordered Many to Many Association

开发者 https://www.devze.com 2023-02-01 05:38 出处:网络
I have a DataMapper many to many relationship, friends, that needs to be kept in the order. Whats the best way to maintain the order? I placed an order property

I have a DataMapper many to many relationship, friends, that needs to be kept in the order. Whats the best way to maintain the order? I placed an order property in the join model, but cannot seem to figure out a good way to update it.

My code:

class Person
  include DataMapper::Resource

  property :id,    Serial
  property :name , String, :required => true

  has n, :friendships, :child_key => [ :source_id ]
  has n, :friends, self, :through => :friendships, :via => :target
end

class Friendship
  include DataMapper::Resource

  property :source_i开发者_Go百科d, Integer, :key => true, :min => 1
  property :target_id, Integer, :key => true, :min => 1

  property :order, Integer

  belongs_to :source, 'Person', :key => true
  belongs_to :target, 'Person', :key => true
end


a = Person.new
b = Person.new
c = Person.new

a.friends = [b, c] # Keep in this order

a.friends == [b, c] # This should be true
a.friends != [c, b]

a.save 

Saving person a should create a friendship between a and b with order value = 1 as well as a second friendship between a and c with order value = 2.

I've been having trouble setting the order values. From what I can tell, the friendships don't actually get created until a is saved, so I can't update them before saving. And I can't updated them after saving because the order is lost.

Any ideas?


You could do this:

Friendship.create(:source => a, :target=> b)
Friendship.create(:source => a, :target=> c)
a.reload
a.friends == [b,c]

This should give you the desired effect, assuming that the order column in your database backend auto increments. If it doesn't then you need to add something like this to your Friendship model:

before :create do
  self.order = Friendship.first(:order=>[:order.desc]).order + 1 rescue 0
end

If you care about the order of these friendships then you also need to do this in the Person model:

has n, :friendships, :child_key => [ :source_id ], :order => [:order.asc]
0

精彩评论

暂无评论...
验证码 换一张
取 消