我想将期中考试和期末考试成绩计算为成绩。例如:
mid test = 80 , final test = 80
(midtest + finaltest)/2 >=80
grade = "A"
是否可以在视图中执行 if 条件并插入数据库?就像是:
if (midtest + finaltest) / 2 >= 80
grade = "A"
elsif (midtest + finaltest)/2 >= 70 and < 80
grade = "B"
elsif (midtest + finaltest) /2 >= 60 and < 70
grade = "C"
因此,在视图中我们不需要text_field
成绩,因此计算会自动插入数据库。
这是解决方案
控制器
def create
@nilai = Nilai.new(params[:nilai])
@nilai.get_grade
respond_to do |format|
if @nilai.save
format.html { redirect_to @nilai, notice: 'Nilai was successfully created.' }
format.json { render json: @nilai, status: :created, location: @nilai }
else
format.html { render action: "new" }
format.json { render json: @nilai.errors, status: :unprocessable_entity }
end
end
end
模型
class Nilai < ActiveRecord::Base
attr_accessible :grade, :id_makul, :id_mhs, :id_nilai, :uas, :uts
def get_grade
@calculate = (self.uas + self.uts)/2
if @calculate >= 80
self.grade = "A"
elsif @calculate >=70 and @calculate < 80
self.grade = "B"
elsif @calculate >=60 and @calculate <70
self.grade = "C"
elsif @calculate >=50 and @calculate <60
self.grade = "D"
else
self.grade = "E"
end
end
end