保存前通过回调来更改属性,但是无法将属性值保存下来? 创建了一个硬件资产 model,每个 record 都有 5 个网卡,所以对应的有 5 个属性值,在保存前我想判断其网卡空闲情况,如果所有网卡都是空值,就标注服务器为空闲:Idle=true
class Hardware < ActiveRecord::Base
attr_accessor :Idle, :Adapter1IP, :Adapter2IP, :Adapter3IP, :Adapter4IP, :Adapter5IP
before_save :idle?
def idle?
if ( self.Adapter1IP.empty? && self.Adapter2IP.empty? || self.Adapter3IP.empty? || self.Adapter4IP.empty? || self.Adapter5IP.empty? )
self.Idle = true
#debugger
else
self.Idle = false
end
end
end
控制器是这样的
class HardwaresController < ApplicationController
def show
@hardware = Hardware.find(params[:id])
end
def new
end
def create
# render plain: params[:hardware].inspect
@hardware = Hardware.new(hardware_params)
@hardware.Adapter1IP=''
@hardware.Adapter2IP=''
@hardware.Adapter3IP=''
@hardware.Adapter4IP=''
@hardware.Adapter5IP=''
@hardware.save!
redirect_to @hardware
end
private
def hardware_params
params.require(:hardware).permit!
end
end
于是问题来了,我创建一个新的 record,可以正常保存,但是保存后显示其 idle 居然是 nil,像这样: 显示资产: #
但是我在 idle?方法中在结尾加了 debugger,显示 self.Idle=true,在 create 方法中,在@hardware.save! 后 debugger,@hardware.Idle也显示为 true,为啥 redirect_to @hardware的时候,页面显示的 Idle 却是 nil 呢?哪有问题?谢谢!
又试了一下,我甚至在 create 中直接写上@hardware.Idle=true,显示出来的属性还是 nil,疯了啊!