-1

I have root with params: localhost:3000/points/mypoint.json?access_token=acuotodEhqyFnVQPJ2AK This root will return list points of all restaurant of users (get user from access_token) My code:

def mypoint
      @locations = Location.select("locations.*")
end
def totalpoint
    @totalpoint = 0
    return 0 if self.user_points.point.count==0
    self.user_points.point.collect { |p| @totalpoint = @totalpoint +p.points}
    return @totalpoint
end
scope :point, where( "points IS NOT ?", nil )

Rabl file:

collection @locations
attributes :name, :totalpoint

Database:

--id---user_id---point_type--restaurant_id---points---
  1       1       favourite       1            50
  2       7       ratings         1            123
  3       7       comments        1            50
  4       7       comments        2            50
  5       7       ratings         2            10

Result:

[
    {
        "name": "quoc",
        "totalpoint": 223
    },
    {
        "name": "Restaurant_id2",
        "totalpoint": 60
    }
]

But this is result list points of all restaurant do not regarding user. Please tell me add condition user_id in totalpoint method. I want to result below Result with user_id = 1:

[
    {
        "name": "quoc",
        "totalpoint": 50
    },
    {
        "name": "Restaurant_id2",
        "totalpoint": 0
    }
]

Result with user_id = 7:

[
    {
        "name": "quoc",
        "totalpoint": 173
    },
    {
        "name": "Restaurant_id2",
        "totalpoint": 60
    }
]

Please give me your solution.Thanks all

4

1 回答 1

0

正确地详细说明您的问题,我花了 15 分钟才明白!

您可以在模型本身内部编写方法。型号名称是什么?通过 user_id 获取点列表

首先找到所有唯一的 user_id 和 restaurant_id

      a=Model.select("DISTINCT(restaurant_id)")
      b=Model.select("DISTINCT(user_id)")

现在 a=[1,2] 和 b=[1,7] 对于这个例子,现在得到每个餐厅的用户收集的所有积分。

     score=Array.new

     b.each do |k|
       rest=Hash.new
       a.each do |f|
          rest[f]=Model.find(:all,:conditions=>["user_id=? and restaurant_id",k,f],:select=>["points"] )
       end
     score<<rest
      end

这会做到的。

于 2013-11-06T08:32:04.533 回答