因此,我正在创建一个评级(明星)模型:
create_table "posts", force: true do |t|
t.string "title"
t.text "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
t.integer "total_stars", default: 0, null: false
t.integer "average_stars", default: 0, null: false
end
create_table "stars", force: true do |t|
t.integer "starable_id"
t.string "starable_type"
t.integer "user_id"
t.integer "number"
t.datetime "created_at"
t.datetime "updated_at"
end所以我已经知道如何得到总恒星:
star.rb:
def add_to_total_stars
if [Post].include?(starable.class)
self.starable.update_column(:total_stars, starable.total_stars + self.number)
end
end但是对于普通的恒星来说:
def calculate_average_stars
if [Post].include?(starable.class)
self.starable.update_column(:average_stars, [SOMETHING MISSING HERE])
end
end 我有点问题。
我想我必须创建一个列来存储文章中的所有numbers,这样我就可以这样做了:
2 + 4 + 2 / total_stars编辑:
好吧,我试过这个:
def calculate_average_stars
if [Post].include?(starable.class)
stars_list = self.starable.stars.map { |t| stars_list = t.number }
self.starable.update_column(:average_stars, stars_list.inject{ |sum, el| sum + el }.to_f / stars_list.size)
end
end但我知道这个错误:
1.9.3-p0 :010 > star5.save
(0.6ms) begin transaction
SQL (1.0ms) UPDATE "posts" SET "total_stars" = 4 WHERE "posts"."id" = 5
SQL (0.8ms) UPDATE "posts" SET "average_stars" = NaN WHERE "posts"."id" = 5
SQLite3::SQLException: no such column: NaN: UPDATE "posts" SET "average_stars" = NaN WHERE "posts"."id" = 5
(0.6ms) rollback transaction
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: NaN: UPDATE "posts" SET "average_stars" = NaN WHERE "posts"."id" = 5关于如何创建这样的表格,有什么建议吗?
发布于 2013-07-24 20:59:09
你知道,如果你已经有了#total_stars,你就不能
def calculate_average_stars
if [Post].include?(starable.class)
self.starable.update_column(:average_stars, total_stars / stars.count)
end
end -and更改posts表,以便average_stars可以成为浮点数而不是整数?
https://stackoverflow.com/questions/17843412
复制相似问题