我看到validates_presence_of
仍然可以使用枚舉。這裏是我的模型
# production.rb
class Production < ActiveRecord::Base
enum status: {active: 1, deactive: 0}
validates_presence_of :status
end
和我rails console
案例1測試你的情況:
2.2.0 :001 > Production.create!
(0.1ms) begin transaction
(0.1ms) rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Status can't be blank
案例2:
2.2.0 :001 > prod = Production.find_or_initialize_by(title: "abc")
Production Load (0.8ms) SELECT "productions".* FROM "productions" WHERE "productions"."title" = ? LIMIT 1 [["title", "abc"]]
=> #<Production id: nil, title: "abc", price: nil, description: nil, status: nil, created_at: nil, updated_at: nil>
2.2.0 :002 > prod.update(price: 23, status: :active)
(0.3ms) begin transaction
SQL (0.8ms) INSERT INTO "productions" ("title", "price", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["title", "abc"], ["price", 23], ["status", 1], ["created_at", "2015-11-04 05:58:43.851364"], ["updated_at", "2015-11-04 05:58:43.851364"]]
(0.7ms) commit transaction
=> true
案例3:
2.2.0 :001 > prod = Production.find_or_initialize_by(title: "def")
Production Load (0.6ms) SELECT "productions".* FROM "productions" WHERE "productions"."title" = ? LIMIT 1 [["title", "def"]]
=> #<Production id: nil, title: "def", price: nil, description: nil, status: nil, created_at: nil, updated_at: nil>
2.2.0 :002 > prod.description = "bla"
=> "bla"
2.2.0 :003 > prod.save!
(0.2ms) begin transaction
(0.1ms) rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Status can't be blank
案例4:
2.2.0 :001 > prod = Production.find_or_initialize_by(title: "def")
Production Load (0.6ms) SELECT "productions".* FROM "productions" WHERE "productions"."title" = ? LIMIT 1 [["title", "def"]]
=> #<Production id: nil, title: "def", price: nil, description: nil, status: nil, created_at: nil, updated_at: nil>
2.2.0 :002 > prod.status = 0
=> 0
2.2.0 :003 > prod.save!
(0.2ms) begin transaction
SQL (0.8ms) INSERT INTO "productions" ("title", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "def"], ["status", 0], ["created_at", "2015-11-04 06:01:16.391026"], ["updated_at", "2015-11-04 06:01:16.391026"]]
(0.7ms) commit transaction
=> true
我使用Rails 4.2.4。
感謝您的信息:) –