任何人都可以解释更新表单的以下奇怪行为吗?
模型 post.rb 包含以下定义
class Post < ActiveRecord::Base attr_accessible :id, :name, :content validates :id, :presence => true, :numericality => { :greater_than_or_equal_to => 100}, :uniqueness => true end
控制器 posts_controller.rb 以这种方式定义更新方法
class PostsController < ApplicationController def update @post = Post.find(params[:id]) respond_to do |format| if @post.update_attributes(params[:post]) format.html { redirect_to @post, notice: 'Post was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @post.errors, status: :unprocessable_entity } end end end
部分视图 _form.rb 还包含使用脚手架生成的标准表达式
<%= form_for(@post) do |f| %> ... <div class="field"> <%= f.label :id %><br /> <%= f.number_field :id %> </div> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :content %><br /> <%= f.text_area :content %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
问题描述:
- 在更新表单中, :id 的无效值给出为 42
- 验证助手处理无效的输入值 (< 100) 并传递通知“Id 必须大于或等于 100”并且数据不会更新
- :id 的字段被替换为一些正确的值,如 123 并再次提交更新帖子按钮
Rails 不是表单接收和更新数据库,而是在 PostsController#show 中抛出异常 ActiveRecord::RecordNotFound
找不到 id=42 的帖子
这里发生了什么 ?为什么会出现异常以及为什么再次传递旧值?