当一条记录被标记为默认时,如何更新所有其他记录?
当有人将其中一个标记为 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为shingara的update_all中的条件是错误的。
应该更新所有 id 不存在的地方。id:
I think the condition is wrong in shingara's update_all.
Should update all where id is not standing.id:
我认为模型和类似的东西更好。你的单元测试失败了吗?
在你的控制器中
在你的代码中你永远不会将default_standp推到@stand中的true
It's better in Model and something like that I suppose. Have you the unit test failing ?
In your controller
In your code you never push default_standing to true in you @standing