新手在这里,尝试在轨道表单上添加一些红宝石规则,特别是如果没有名称,我不想允许创建项目
class Idea < ActiveRecord::Base
mount_uploader :picture, PictureUploader
belongs_to :project
validates :name, presence: true, allow_nil: false
end
如果我从我的应用程序创建一个新项目,那么工作顺利,但如果我从rails控制台创建一个项目,则不会发生相同的情况。如果在应用程序或rails控制台中创建了没有名称的项目,我怎样才能避免创建项目?
答案 0 :(得分:3)
问题是您必须设置allow_blank: false
而不是allow_nil: false
。
在Ruby中, empty string
是 not nil
。
"".nil?
#=> false
"".blank?
#=> true
像这样更新您的模型
class Idea < ActiveRecord::Base
mount_uploader :picture, PictureUploader
belongs_to :project
validates :name, presence: true, allow_blank: false
end
如果您想了解nil
和blank
之间的差异,请参阅此 SO 帖子。
请参阅 Guides 了解allow_blank
答案 1 :(得分:-1)
从控制台试试: -
Idea.create(:name => "Something")
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控制台输出: -
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
如果未提供名称字段,则无法创建
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>