我试图制作一个基于社交网络的咖啡馆搜索服务项目,我希望按照其他用户提供的点对咖啡馆阵列进行排序。
select
callcategory
,total
,substring(datename(weekday, resolveddate), 1, 3) as day
,datepart(week, resolveddate) as week
,substring(datename(month, resolveddate), 1, 3) as month
,datepart(year, resolveddate) as year
,datepart(week, today) as currentweek
,substring(datename(month, today), 1, 3) as currentmonth
,datepart(year, today) as currentyear
,case when datename(year, resolveddate) + datename(week, resolveddate) = datename(year, today) + datename(week, today) then 'yes' else 'no' end as isthisweek
,case when datename(year, resolveddate) + datename(week, resolveddate) = datename(year, oneweekago) + datename(week, oneweekago) then 'yes' else 'no' end as islastweek
,case when datename(year, resolveddate) + datename(month, resolveddate) = datename(year, today) + datename(month, today) then 'yes' else 'no' end as isthismonth
,case when datename(year, resolveddate) = datename(year, today) then 'yes' else 'no' end as isthisyear
,case when resolveddate = today then 'yes' else 'no' end as istoday
,case when datename(year, resolveddate) + datename(week, resolveddate) = datename(year, fourweeksago) + datename(week, fourweeksago) then 'yes' else 'no' end as monthold
from
(
select
callcategory,
cast(resolveddate as date) as resolveddate,
cast(getdate() as date) as today,
cast(dateadd(week, -1, getdate()) as date) as oneweekago,
cast(dateadd(week, -4, getdate()) as date) as fourweeksago,
count(*) as total
from prcdepartmenthelpdesks
where supportteam = 'some team'
and resolveddate >= '2016-02-09'
group by callcategory, cast(resolveddate as date)
) grouped;
这是咖啡馆模特,' avg'是用户给出的平均点数。
class Cafe < ActiveRecord::Base
belongs_to :user
has_many :posts, dependent: :destroy
has_many :tags, dependent: :destroy
has_many :payments, dependent: :destroy
has_many :payinfos, dependent: :destroy
mount_uploader :image,CafeimageuploaderUploader
mount_uploader :thumnail,CafeimageuploaderUploader
geocoded_by :address
after_validation :geocode
def avg
total = 0
posts.each do |c|
total += c.score
end
if posts.count == 0
0
else
total.to_f / posts.count
end
end
end
此处的帖子列。
我想要做的是通过这个平均动作对新的Cafe数组进行排序。(它被称为模型动作,对吧?)
给我一些建议,谢谢。
答案 0 :(得分:0)
我会将一个属性average_score
添加到cafe模型中,并使用after_save回调方法来发布模型。如果邮件将被保密,您可以获取咖啡馆的所有帖子(通过外键),计算平均分数并将其保存到咖啡馆,或者您触发咖啡馆模型的方法来执行此操作。所以你可以轻松地对咖啡馆进行分类。
答案 1 :(得分:0)
让我们使用db查询,效率更高。 (假设Cafe's table name is cafes
)
Cafe.joins("LEFT OUTER JOIN (SELECT cafe_id, AVG(score) AS avg_score
FROM posts
GROUP BY cafe_id
) AS temp
ON cafes.id = temp.cafe_id
").order('temp.avg_score DESC NULLS LAST')
理想情况下,我们先计算临时表中的平均分数,然后通过Cafe
加入cafe_id
。之后,我们可以轻松地将order
与avg_score
一起使用。
由于我们使用的是LEFT OUTER JOIN
,因此avg_score
的{{1}} cafe
没有任何帖子NULL
,因此我们使用NULLS LAST
来确保咖啡馆将到底。