开发者

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

开发者 https://www.devze.com 2023-03-16 20:23 出处:网络
Here is the setup: Model class ListItem < ActiveRecord::Base belongs_to :list validates :title, :presence => true, :length => { :minimum => 1 }

Here is the setup:

Model

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

When the list_item.title is populated it works fine. When a list_item.title of length 0 is submitted it doesn't fail gracefully. 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 LI开发者_运维百科MIT 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.

Thanks


You are missing format.js and the block for it:

  # 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
0

精彩评论

暂无评论...
验证码 换一张
取 消