所以我正在创建一个评级(明星)模型:
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
有关如何创建此类表的任何建议吗?
答案 0 :(得分:1)
你知道,如果你已经有#total_stars,你不能只做
def calculate_average_stars
if [Post].include?(starable.class)
self.starable.update_column(:average_stars, total_stars / stars.count)
end
end
- 更改posts表,以便average_stars可以是float而不是整数?