Rails update_attributes not working



在我的Rails应用程序中,update_attribute似乎不工作。我正在尝试更新一个名为billed的布尔字段。同样的命令也适用于其他两个表。

rails console输出:

>> Expense.find(28).update_attributes(:billed => true)
=> false
>> Expense.find(28).billed
=> false

expenses_controller.rb:

# PUT /expenses/1
# PUT /expenses/1.json
def update
  @expense = Expense.find(params[:id])
  respond_to do |format|
    if @expense.update_attributes(params[:expense])
      format.html { redirect_to @expense, notice: 'Expense was successfully updated.' }
      format.json { render json: @expense }
    else
      format.html { render action: "edit" }
      format.json { render json: @expense.errors, status: :unprocessable_entity }
    end
  end
end

费用有以下验证:

  validates_presence_of :employee_id       # Declare a required field
  validates_presence_of :unitcost          # Declare a required field
  validates_presence_of :quantity          # Declare a required field
  validates_presence_of :exp_date          # Declare a required field
  validates_presence_of :category_id       # Declare a required field
  validates_presence_of :description       # Declare a required field
  validates_presence_of :markup            # Declare a required field
  validates :markup, :format => { :with => /^d{3}$/}, :numericality => {:greater_than => 0}
  validates :unitcost, :format => { :with => /Ad+(?:.d{0,2})?z/}, :numericality => {:greater_than => 0}
  validates_numericality_of :quantity, :only_integer => true, :message => "Can only be whole number."

谢谢你的帮助!

使用 update_attribute 代替 update_attributes 更新单列

API

update_attribute

更新单个属性并保存记录,而无需经过正常的验证程序。这对布尔值尤其有用现有记录上的标志。Base中的常规update_attribute方法当验证模块混合在一起时,替换为this,哪个默认为

Expense.find(28).update_attribute(:billed => true)

相关内容

  • 没有找到相关文章

最新更新