Reputation: 5953
In my Rails app, update_attribute
seems not working. I'm trying to update a boolean field called billed
. The same command works great for two other tables.
Output of 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
Expenses has these validations:
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."
Thanks for the help!
Upvotes: 2
Views: 2148
Reputation: 33542
Use update_attribute
instead of update_attributes
to update single column.
From the API
update_attribute
Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default
Expense.find(28).update_attribute(:billed => true)
Upvotes: 4