"validates_presence_of" not working

Hi, guys,

I’m learning to use Rails, and, while reading the “Rails: Up And
Running” book, I tried to make an insertion validation, using the
following code:

class Photo < ActiveRecord::Base
validates_presence_of :filename

It simply didn’t work, the validation does nothing and an insertion
with an empty field returns TRUE.

What’s wrong?

On 5/11/07, diogobaeder.com.br [email protected] wrote:

It simply didn’t work, the validation does nothing and an insertion
with an empty field returns TRUE.

What’s wrong?


Uh, well, it works for me. You’ll need to provide more information
for anyone to be able to help you I think. In particular, exactly
what’s returning “TRUE”, and what you have in your record at the time.


$ cat db/migrate/001_create_initial_tables.rb
class CreateInitialTables < ActiveRecord::Migration
def self.up
create_table :photos do |t|
t.column :filename, :string

def self.down
drop_table :photos

$ cat app/models/photo.rb
class Photo < ActiveRecord::Base
validates_presence_of :filename

$ script/console
Loading development environment.

=> false

Photo.new(:filename => ‘’).valid?
=> false

Photo.new(:filename => ‘blah’).valid?
=> true

Oops, sorry George, indeed I should have put some more information
about what’s happening and what’s the scene here…

There’s a table in the db called “photos”, with two columns, “id” and
“filename”. “filename” is set for “NULL” as default, but I want to use
“validates_presence_of” as a mean to verify the field entry on the
console (“script/console”).

When I do a “photo=Photo.new”, and a “photo.save”, in the console, it
should return “false”, and generate the error strings for future
analisys, but it’s returning “true” and it creates a new record in my
db with the “filename” field empty.

This was not supposed to happen because of
“validate_presence_of :filename”, which I wrote in the “photo.rb”
model file.

Do I need to put more information? Thanks a lot, George!


Hi, where’s the code where you’re trying to save the instance to the
database? This should be somewhere in your controller code. Also, can
provide your script/console transcript similar to what George provided?



Hi, George,

Can’t understand. Yesterday it was returning “true” in the console,
with empty field, and today, after I answered your message for the
first time, I tested it again, and it’s returning “false”!!!

I tried to restart the server, and nothing, and, just now that I
restarted my computer, it’s working! What’s happening? Any clue?

Thanks, George, again!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs