开发者

Rails 3 - how do you use methods like where and sum on proxy_targets in association extension methods?

in my app, 2 peope can be friends via a friendships model and they can create records of how much money they lent to the other friend.

I want to create something like this

@friendship.receipts.balance_for(@user) which will return how much @user owes to or is owed by their friend in this friendship. i.e. if it returns -50 they owe $50 or if its positive they are owed $50

Id also like to be able further scope this for use in live filt开发者_如何学Cering (by dates, tags etc) i.e. would like this

@friendship.receipts.where(:tag => "groceries).balance_for(@user)

My first attempt was to create an association extension on the friendship model

class Friendship < ...
  has_many :receipts do
    def balance_for(user)
      user_total_spent = proxy_target.sum(:value, :payer_id => user.id)
      friend_total_spent = proxy_target.sum(:value, :payer_id => friend.id)
      return user_balance = user_total_spent - friend_total_spent
    end
  end
end

but unfortunately the method sum cant be used on proxy_target because it returns a plain array and not the Activerecord::Relation class sum expects.

Whats a good workaround this??? Id like to create a method that can be called on scoped results.


You might want to try simply calling sum without an explicit receiver. I'm looking for the solution to a similar problem, and found what looks like the answer to your question here: http://withoutscope.com/2008/8/22/don-t-use-proxy_target-in-ar-association-extensions

Unfortunately, it doesn't solve my problem. I'm trying to figure out how to extend models retrieved through my association extension with a module where the module name is a member of the proxy's owner.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜