ruby-on-rails - Rails,如何处理验证响应。现在我收到 406 错误

标签 ruby-on-rails ruby ruby-on-rails-3

这是设置:

型号

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/

相关文章:

c++ - C++ 和 Rails 应用程序之间的交互

mysql - 差点搞乱了我在 heroku 上的数据库 : mysql error on db:pull

ruby-on-rails - 将 master 重置为空状态

ruby-on-rails - Rails form_for :remote=>true is not calling js method

ruby-on-rails - 默认情况下,activerecord 模型对所有表列都有 attr_accessor 是否正确?

python - 这段 python 代码有什么问题吗,为什么它运行起来比 ruby​​ 慢?

Ruby 1.9 - 无效的多字节字符 (US-ASCII)

ruby-on-rails - 在 rails_admin 中,如何过滤关联计数?

ruby-on-rails - 使用 Google-Maps-For-Rails 更新更改模型地址的坐标

ruby-on-rails-3 - 无法让 Cucumber/Capybara 找到单选按钮