简体   繁体   中英

Rails before_save is not working

I want to calculate @rating of each item before creating/updating. here is my model:

class SmsController < ApplicationController
  before_save :calculate_rating
  def new
  end

  def create
  end

  def show
  end

  def destroy
  end

  private
    def calculate_rating
        self.rating=self.happy-self.sad+(3*self.report)
    end
end

but when I add some random seeds to the DB the rating attribute for all of them is nil. Am I doing something wrong? Thanks in advance!

A before_save callback is part of the ActiveRecord module (for models) in Rails. ActiveRecord::Callbacks

So, your before_save directive and method would go in the Sms model versus the SmsController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM