2013-07-24 34 views
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 

有關如何創建此類表的任何建議?

+0

so a star belongs_to:starable,and post has_many:stars - post.rb中的方法中的starable.class是什麼?並且是[Post] .include?真的需要一個包含Post類作爲唯一元素的數組,或者你的意思是self.include? – bgates

+0

@bgates只要檢查可疑物是否爲'Post',它實際上與方法無關。 – alexchenco

+0

哦#add_to_total_stars和calculate_average_stars在star.rb中,對嗎?不是post.rb. – bgates

回答

1

你知道,如果你已經有了#total_stars,不能只是你

def calculate_average_stars 
    if [Post].include?(starable.class) 
    self.starable.update_column(:average_stars, total_stars/stars.count) 
    end 
end 

- 和改變的職位表,以便average_stars可以是浮動的,而不是一個整數?