【发布时间】:2016-02-11 07:16:21
【问题描述】:
我正在尝试制作一个基于社交网络的咖啡馆搜索服务项目,我想按其他用户给出的点数对咖啡馆数组进行排序。
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 模型,'avg' 是用户给出的平均分。
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :content , null: false, default: ""
t.string :image
t.string :address , null: false, default: "위치정보 없음"
t.string :hashstr
t.datetime :writtentime
t.integer :user_id
t.integer :cafe_id , null: false, default: 0
t.integer :score, default:0
t.timestamps null: false
end
end
end
这里是帖子专栏。
我想做的是通过这个 avg 动作对新的 Cafe 数组进行排序。(它被称为模型动作,对吗??)
给我一些建议,谢谢。
【问题讨论】:
-
旁注:
posts.each { |c| total += c.score }效率很低。改用posts.sum(&:score)将计算移至db层。
标签: ruby-on-rails arrays ruby sorting