你好,我是Ruby的新手,我正在尝试在我的项目控制器中创建一个方法,如下所示:
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"
我该怎么解决?
最佳答案
根据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
关于ruby-on-rails - Controller 中的NoMethodError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45114316/