你好我是Ruby的新手,我正试图在我的Project控制器中创建一个方法,如下所示:
def update_phase
@project = Project.find(params[:id])
diff = (Date.current.year * 12 + Date.current.month) - (@project.starting.year * 12 + @project.starting.month)
case
when diff >= 30
@project.process = 11
.
.
.
when diff >= 0
@project.process = 1
else
@project.process = 0
end
proc = @project.process.to_f
case
when proc >= 9
@project.phase = "Final"
when proc >= 5
@project.phase = "Desarrollo"
when proc >= 1
@project.phase = "Inicio"
else
@project.phase = "Error en el proceso"
end
end
starting
是模型中的时间戳。在我看来,我有:
<% @project.update_phase %>
但我收到错误:"NoMethodError in Projects#show"
我该如何解决这个问题?
答案 0 :(得分:0)
取决于starting
来自何处或何处,您可以使用before_save
回调,这样每次您要创建新记录时,都会触发update_phase
方法并从当前项目对象中分配process
和phase
的值:
class Project < ApplicationRecord
before_save :update_phase
...
def update_phase
diff = (Date.current.year * 12 + Date.current.month) - (self.starting.year * 12 + self.starting.month)
case
when diff >= 30
self.process = 11
...
end
proc = self.process.to_f
case
when proc >= 9
self.phase = 'Final'
...
end
end
end