在我的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 => /\A\d+(?:\.\d{0,2})?\z/}, :numericality => {:greater_than => 0}
validates_numericality_of :quantity, :only_integer => true, :message => "Can only be whole number."
感谢您的帮助!
答案 0 :(得分:4)
使用 update_attribute
代替 update_attributes
更新单个列。
来自 API
update_attribute
更新单个属性并保存记录而不经过 正常的验证程序。这对布尔值特别有用 现有记录上的标志。 Base中的常规update_attribute方法 当混合验证模块时,将替换为this 默认情况下
Expense.find(28).update_attribute(:billed => true)