2014-06-19 96 views
2

在我的Rails應用程序中,update_attribute似乎無法正常工作。我試圖更新一個名爲billed的布爾字段。同樣的命令對另外兩個表很有用。Rails update_attributes不起作用

輸出的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." 

感謝您的幫助!

+1

你對費用驗證其 ? –

+0

是的 - 我會補充問題。 – Reddirt

+0

使用'update_attribute'而不是'update_attributes'來更新單列。 – Pavan

回答

4

使用update_attribute,而不是update_attributes更新單列。

API

update_attribute

更新單個屬性並保存記錄,而無需通過 會正常驗證程序。這對於現有記錄上的布爾值 標誌特別有用。在基地 常規update_attribute方法替換爲當驗證模塊,混合,它是默認

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