控制器中的NoMethodError

时间:2017-07-15 04:00:13

标签: ruby-on-rails ruby ruby-on-rails-4

你好我是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" 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

取决于starting来自何处或何处,您可以使用before_save回调,这样每次您要创建新记录时,都会触发update_phase方法并从当前项目对象中分配processphase的值:

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