2010-10-13 34 views
0

我試圖將所有其他記錄的default_standing字段更改爲FALSE,當有人將其標記爲TRUE時。這樣,我只會在表中有一個默認記錄。以下是我在這兩個創建並在我的控制器更新正在做,但它似乎並不奏效:如何在標記爲默認時更新所有其他記錄?

def update 
    @standing = Standing.find(params[:id]) 

    if @standing.default_standing 
     @standings = Standing.where(["default_standing = ? AND id != ?", true, params[:id]]) 

     @standings.each do |s| 
     s.default_standing = false 
     s.save! 
     end 
    end 

    respond_to do |format| 
     if @standing.update_attributes(params[:standing]) 
     format.html { redirect_to(@standing, :notice => 'Standing was successfully updated.') } 
     format.xml { head :ok } 
     else 
     format.html { render :action => "edit" } 
     format.xml { render :xml => @standing.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

回答

1

我覺得條件是錯誤的shingara的update_all。 應該更新所有id不存在的地方.id:

class Standing 

    def self.all_false_instead_of(standing) 
    return if standing.default_standing 
    Standing.update_all(["default_standing = ?", false], ['id <> ?', standing.id]) 
    standing.update_attributes!(:default_standing, true) 
    end 
end 
+0

我得到以下錯誤:SQLite3 :: SQLException:接近「7」:語法錯誤:更新「積分榜」SET default_standing = false WHERE(id不是7) – Rob 2010-10-13 16:53:59

+0

更正SQL不等於 – Oliver 2010-10-13 17:05:05

+0

更改SQL不等於和得到以下錯誤:SQLite3 :: SQLException:沒有這樣的列:false:更新「積分榜」SET default_standing = false其中(id <> 7) – Rob 2010-10-13 20:46:53

1
class Standing 

    def self.all_false_instead_of(standing) 
    return if standing.default_standing 
    Standing.update_all("default_standing = false", {:id => standing.id}) 
    standing.update_attributes!(:default_standing, true) 
    end 
end 

這是在型號和類似的東西,我想更好。你的單元測試失敗了嗎?

在你的控制器

def update 
    @standing = Standing.find(params[:id]) 
    Standing.all_false_instead_of(@standing) 
end 

在你的代碼永遠不會推default_standing爲true,你@standing

+0

這似乎不起作用。它允許我創建或更新我的記錄而沒有錯誤,但它根本不會翻轉其他記錄。 – Rob 2010-10-13 13:53:43

相關問題