-1

私はスターモデルモデルを持っており、ポストモデルへの列が含まれtotal_starsています:average_stars

  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  "average_stars", default: 0, null: false
    t.integer  "total_stars",   default: 0, null: false
  end

def calculate_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, starable.total_stars / starable.stars.count) end end

したがって、問題はaverage_stars3.6最終結果がただの場合3です。5 つ星評価システムに適した計算または概算の種類がよくわかりません。しかし、次のようにしたいと思います: 1, 1.5, 2, 2.5...

average_starsその結果を達成するために列を変更する方法の提案はありますか?

4

2 に答える 2

2

平均列を整数として宣言する代わりに、浮動小数点数 (または小数) として宣言します。

t.float  "average_stars", default: 0, null: false

次に、計算を行っているときに次のことを行います。

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

これにより、丸められた/切り捨てられた整数ではなく、10 進数の値が得られます。そこ.to_fが重要な部分です。

丸めたり、固定小数点数のみにしたい場合は、移行で Decimal 列を使用するか (:limit を取ります)、数学的なことを行います。

((starable.total_stars.to_f / starable.stars.count) * 100).round / 100.0
于 2013-07-26T06:07:14.513 に答える
1
def calculate_average_stars
  if starable.is_a?(Post) 
    exact_average = starable.total_stars.to_f / starable.stars.count
    rounded_average = exact_average - (exact_average % 0.5)
    starable.update_column(:average_stars, rounded_average) 
  end
end
于 2013-07-26T06:07:45.440 に答える