当一个记录为默认记录时,如何更新所有其他记录?

时间:2010-10-13 12:32:35

标签: ruby-on-rails activerecord controller

当有人将其标记为TRUE时,我尝试将所有其他记录的所有default_standing字段更改为FALSE。这样我在表格中只会有一条默认记录。以下是我在控制器中创建和更新时所做的事情,但它似乎不起作用:

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

2 个答案:

答案 0 :(得分: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

在Model中它更好,我想的更像。你的单元测试失败了吗?

在您的控制器中

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

在你的代码中,你永远不会在你的@standing

中将default_standing推送到true

答案 1 :(得分: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