简体   繁体   English

allow_nil:false无法从rails控制台运行

[英]allow_nil: false does not work from rails console

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 新手在这里,尝试在rails表单上添加一些ruby规则,特别是我不想允许创建一个项目,如果这个没有名字

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. 如果我从我的应用程序创建一个新项目,可以顺利运行,但如果我从rails控制台创建一个项目,则不会发生相同的情况。 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? 如果在应用程序或rails控制台中创建了这个项目,我怎么能避免创建没有名称的项目?

The problem is you have to set allow_blank: false instead of allow_nil: false . 问题是您必须设置allow_blank: false而不是allow_nil: false

In Ruby an empty string is not nil . 在Ruby中, empty string 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. 如果您想知道nilblank之间的差异,请参阅此SO帖子。

Refer these Guides for allow_blank 请参阅这些指南以了解allow_blank

Try this from console:- 从控制台试试: -

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

Rails console output:- Rails控制台输出: -

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:- Rails控制台输出: -

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM