这是设置:
型号
class ListItem < ActiveRecord::Base
belongs_to :list
validates :title, :presence => true, :length => { :minimum => 1 }
end
Controller
# POST /list_items
# POST /list_items.xml
def create
@list = List.find(params[:list_id])
@list_item = @list.list_items.build(params[:list_item].merge(:user_id => current_user.id))
respond_to do |format|
if @list_item.save
format.js
else
render :js => "alert('enter at least one character please!');"
end
end
end
当填充 list_item.title 时,它工作正常。当提交长度为 0 的 list_item.title 时,它不会优雅地失败。在我看到的日志中:
Started POST "/lists/7/list_items" for 127.0.0.1 at Wed Jun 29 18:04:26 -0700 2011
Processing by ListItemsController#create as
Parameters: {"list_item"=>{"completed"=>"0", "title"=>""}, "authenticity_token"=>"9yJ9yBo883gEOhl0lKkTzDMTDLXg/Fjx5e9wYonf3yE=", "utf8"=>"✓", "list_id"=>"7"}
List Load (0.4ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = 7 LIMIT 1
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 6 LIMIT 1
SQL (0.2ms) BEGIN
SQL (0.2ms) ROLLBACK
Rendered list_items/_list_item.html.erb (2.1ms)
Rendered list_items/create.js.erb (3.8ms)
Completed 406 Not Acceptable in 201ms (Views: 33.3ms | ActiveRecord: 7.2ms)
在浏览器中我看到:
POST http://localhost:3000/lists/7/list_items 406 (Not Acceptable)
如果 list_item.title 的长度为 0,我在不出错方面做错了什么。我只需要 Rails 响应并提醒用户至少输入一个字符。
谢谢
最佳答案
你缺少 format.js
和它的代码块:
# POST /list_items
# POST /list_items.xml
def create
@list = List.find(params[:list_id])
@list_item = @list.list_items.build(params[:list_item].merge(:user_id => current_user.id))
respond_to do |format|
if @list_item.save
format.js
else
format.js { # <-- Missing this
render :js => "alert('enter at least one character please!');"
}
end
end
end
关于ruby-on-rails - Rails,如何处理验证响应。现在我收到 406 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6528977/