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 end It simply didn't work, the validation does nothing and an insertion with an empty field returns TRUE. What's wrong?
on 2007-05-11 06:18
on 2007-05-11 06:40
On 5/11/07, diogobaeder.com.br <firstname.lastname@example.org> wrote: > > 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 $ script/console Loading development environment. >> Photo.new.valid? => false >> Photo.new(:filename => '').valid? => false >> Photo.new(:filename => 'blah').valid? => true
on 2007-05-11 19:07
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! Diogo
on 2007-05-11 19:20
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!
on 2007-05-11 20:01
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? Thanks, -Conrad