3

Newbie here, trying to add some rules to a ruby on rails form, specifically I don't want to allow the creation of an item if this has not a name

class Idea < ActiveRecord::Base
mount_uploader :picture, PictureUploader
belongs_to :project
validates :name, presence: true, allow_nil: false
end

Works smoothly if I create a new item from my app, but not happens the same if I create one item from rails console. How can I avoid the creation of an item without name, no matter if this has been created in the app or in the rails console?

Pavan
  • 33,316
  • 7
  • 50
  • 76
malditojavi
  • 1,074
  • 2
  • 14
  • 28

2 Answers2

3

The problem is you have to set allow_blank: false instead of allow_nil: false.

In Ruby an empty string is not nil.

"".nil?
#=> false

"".blank?
#=> true

Update your model like this

class Idea < ActiveRecord::Base
  mount_uploader :picture, PictureUploader
  belongs_to :project
  validates :name, presence: true, allow_blank: false
end

If you want know the differences between nil and blank,see this SO post.

Refer these Guides for allow_blank

Pavan
  • 33,316
  • 7
  • 50
  • 76
  • 2
    I highly recommend using `allow_blank` instead of `allow_nil` like this answer states. But also consider using the `nilify_blanks` gem to make sure you store `NULL`s instead of empty strings in the DB for empty values. – Chris Peters May 24 '14 at 19:01
-1

Try this from console:-

Idea.create(:name => "Something")

Rails console output:-

1.9.3-p385 :005 > c  = CabinNumber.create(:name => "Something")
(0.2ms)  begin transaction
SQL (1.1ms)  INSERT INTO "cabin_numbers" ("created_at", "name", "status", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Sun, 25 May 2014 00:02:04 IST +05:30], ["name", "Something"], ["status", false], ["updated_at", Sun, 25 May 2014 00:02:04 IST +05:30]]
(139.6ms)  commit transaction
=> #<CabinNumber id: 11, name: "Something", status: false, created_at: "2014-05-24 18:32:04", updated_at: "2014-05-24 18:32:04"> 

OR

idea = Idea.new(:name => "hello")
idea.save

Rails console output:-

1.9.3-p385 :007 > c  = CabinNumber.new(:name => "hello")
=> #<CabinNumber id: nil, name: "hello", status: false, created_at: nil, updated_at: nil> 
1.9.3-p385 :008 > c.save
(0.1ms)  begin transaction
SQL (1.0ms)  INSERT INTO "cabin_numbers" ("created_at", "name", "status", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Sun, 25 May 2014 00:02:57 IST +05:30], ["name", "hello"], ["status", false], ["updated_at", Sun, 25 May 2014 00:02:57 IST +05:30]]
(155.0ms)  commit transaction
=> true 

Cannot create if name field is not provided

1.9.3-p385 :003 > c  = CabinNumber.create()
(0.2ms)  begin transaction
(0.1ms)  rollback transaction
=> #<CabinNumber id: nil, name: nil, status: false, created_at: nil, updated_at: nil> 
Shamsul Haque
  • 2,441
  • 2
  • 18
  • 20