所以我正在创建一个评级(星)模型:
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
所以我已经知道如何获得总星数:
星号.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
有关如何创建此类表的任何建议?