0
所以我創建一個等級(星級)型號AVERAGE_RATING柱:的評級模型的
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
編輯:
OK,我嘗試這樣做:
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
有關如何創建此類表的任何建議?
so a star belongs_to:starable,and post has_many:stars - post.rb中的方法中的starable.class是什麼?並且是[Post] .include?真的需要一個包含Post類作爲唯一元素的數組,或者你的意思是self.include? – bgates
@bgates只要檢查可疑物是否爲'Post',它實際上與方法無關。 – alexchenco
哦#add_to_total_stars和calculate_average_stars在star.rb中,對嗎?不是post.rb. – bgates