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
end
It simply didn't work, the validation does nothing and an insertion
with an empty field returns TRUE.
What's wrong?
Hi,
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.
Regards.
George.
$ cat db/migrate/001_create_initial_tables.rb
class CreateInitialTables < ActiveRecord::Migration
def self.up
create_table :photos do |t|
t.column :filename, :string
end
end
def self.down
drop_table :photos
end
end
$ cat app/models/photo.rb
class Photo < ActiveRecord::Base
validates_presence_of :filename
end
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!
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?
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 you provide your script/console transcript similar to what George provided?