views:

43

answers:

2

I am trying to change all of the default_standing fields to FALSE for all other records when someone marks one as TRUE. That way I will only ever have one default record in the table. Here is what I am doing in both create and update in my controller, but it doesn't seem to be working:

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  A: 
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

It's better in Model and something like that I suppose. Have you the unit test failing ?

In your controller

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

In your code you never push default_standing to true in you @standing

shingara
This doesn't appear to work either. It allows me to create or update my records without errors, but it's not flipping the other records at all.
Rob
+1  A: 

I think the condition is wrong in shingara's update_all. Should update all where id is not standing.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
Oliver
I get the following error:SQLite3::SQLException: near "7": syntax error: UPDATE "standings" SET default_standing = false WHERE (id is not 7)
Rob
Corrected the SQL for not equal
Oliver
Changed the SQL for not equal and get the following error: SQLite3::SQLException: no such column: false: UPDATE "standings" SET default_standing = false WHERE (id <> 7)
Rob
Sorry my mistake again - have corrected to ["default_standing = ?", false]
Oliver
That did it. Thanks!
Rob