:allow_nil only working in Console?

Hello there,

I have the following Book model, where users can enter the Title of the book and optionally the format of the ISBN-code shall be validated, but only if the user filled the ISBN field:

class Book < ActiveRecord::Base   # associations   belongs_to :user, :counter_cache => true

  # validations   validates_presence_of :title   validates_format_of :isbn, :with => /[0-9\-a-zA-Z]{10}|[0-9\-a-zA-Z] {13}/, :allow_nil => true   validates_existence_of :user

  attr_protected :user_id end

When I create a book on the console sans ISBN code, it works perfectly fine:

b = Book.new

=> #<Book id: nil, title: nil, author: nil, isbn: nil, description: nil, user_id: nil, created_at: nil, updated_at: nil>

b.user_id = 1

=> 1

b.title = "Book #1"

=> "Book #1"


=> true

When I enter a non isbn-10 or isbn-13 code, it properly raises the error:

b.title = "Book #2"

=> "Book #2"

b.isbn = "abc"

=> "abc"


=> false


=> #<ActiveRecord::Errors:0x2409564 @base=#<Book id: nil, title: "Book #2", author: nil, isbn: "abc", description: nil, user_id: 1, created_at: nil, updated_at: nil>, @errors={"isbn"=>["is invalid"]}>

So far so good. Now when I do the same in the browser & create an ISBN- less book, it says:

1 error prohibited this book from being saved There were problems with the following fields: Isbn is invalid

And the params looking like this: {"commit"=>"Create", "authenticity_token"=>"5c27df353e84da4378277ff8201bcacdb394a0d4", "action"=>"create", "controller"=>"books", "user_id"=>"1", "book"=>{"isbn"=>"", "title"=>"abc", "author"=>"", "description"=>""}}

Why is this? Shouldn't :allow_nil work there, too?

Or did I miss something? -J

not sure, but most likely "isbn"=>"" is an empty string and that for not nil

at least erb: "".nil? => false


yeah - you're right.. didn't expect it that way entirely... but a simple fix for this e.g. that one: http://opensoul.org/2007/2/7/validations-on-empty-not-nil-attributes