在我的应用程序中,2个人可以通过友谊模式成为朋友,他们可以创建他们借给其他朋友多少钱的记录。
我想创建像这样的东西
@ friendship.receipts.balance_for(@user)将返回@user在这段友谊中欠他们的朋友或欠他们多少钱。即如果它返回-50则他们欠50美元,或者如果它是正数则他们欠50美元
我也希望能够进一步将其范围用于实时过滤(按日期,标签等),即希望如此
@ friendship.receipts.where(:tag =>“groceries).balance_for(@user)
我的第一次尝试是在友谊模型上创建一个关联扩展
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
但遗憾的是,方法sum不能用于proxy_target,因为它返回一个普通数组,而不是Activerecord :: Relation类和sum。
这是一个很好的解决方法吗?我想创建一个可以在范围结果上调用的方法。
答案 0 :(得分:1)
你可能想尝试简单地在没有显式接收器的情况下调用sum。我正在寻找类似问题的解决方案,并在此处找到了您的问题的答案:http://withoutscope.com/2008/8/22/don-t-use-proxy_target-in-ar-association-extensions
不幸的是,它并没有解决我的问题。我试图找出如何通过我的关联扩展检索的模型扩展模块名称是代理所有者的成员模块。