简体   繁体   English

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

[英]Rails, how to handle validation responses. Right now I get 406 errors

Here is the setup:这是设置:

Model Model

class ListItem < ActiveRecord::Base
  belongs_to :list
  validates :title, :presence => true, :length => { :minimum => 1 }
end

Controller 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

When the list_item.title is populated it works fine.当 list_item.title 被填充时,它工作正常。 When a list_item.title of length 0 is submitted it doesn't fail gracefully.当提交长度为 0 的 list_item.title 时,它不会优雅地失败。 In the logs I see:在我看到的日志中:

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)

In the browser I see:在浏览器中我看到:

 POST http://localhost:3000/lists/7/list_items 406 (Not Acceptable)

What am I doing wrong in terms of not erroring if the list_item.title has a length of 0. I just need rails to respond back and alert the user to enter at least one character.如果 list_item.title 的长度为 0,我在不出错方面做错了什么。我只需要 rails 来响应并提醒用户输入至少一个字符。

Thanks谢谢

You are missing format.js and the block for it:您缺少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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM