开发者

How do I update all other records when one is marked as default?

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开发者_JAVA技巧 @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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜