只允许属性的特定词

Allow Only Specific Words for Attribute

如何将字符串字段中允许的字符串限制为特定单词?

示例:我有一个模型属性 animal:string,我想完全接受 ["dog", "cat", "bird", "fish"]。其他一切都会使对象无效。

您可以在您的表单中使用 select 字段,并在您的模型中写入:

module Animal
    dog = 1
    cat = 2
    bird = 3
    fish = 4
end

并以游览形式:

<%= f.select  :animal, { "dog" => 1, "cat" => 2, "bird" => 3, "fish" => 4} %>

为您的模型添加 inclusion 验证:

validates :animal, inclusion: { in: %w(dog cat bird fish) }

正如我所说,我会选择 Rails Enum 功能。

class ModelName < ActiveRecord::Base
  enum animals: %w(dog cat)
  # ...
end

There is one gotcha 您可能会注意到,因为这称为枚举:您需要将数据库列更新为整数值。 Rails 会自动在整数值和数组中的索引之间进行隐式映射

如果您使用 Enum 功能,只需一行代码,Rails 将为您生成几个辅助方法:

# Query method
model_name.dog?
model_name.cat?
#..

# Action method
model_name.cat!
model_name.dog!
#..

# List of statuses and their corresponding values in the database.
model_name.animals

久经考验:

[arup@app]$ rails c
Loading development environment (Rails 4.1.1)
[1] pry(main)> Pet.create!(animals: 'cat')
   (0.3ms)  BEGIN
  SQL (0.9ms)  INSERT INTO "pets" ("animals", "created_at", "updated_at") VALUES (, , ) RETURNING "id"  [["animals", 1], ["created_at", "2015-02-19 18:27:28.074640"], ["updated_at", "2015-02-19 18:27:28.074640"]]
   (42.2ms)  COMMIT
=> #<Pet id: 5, animals: 1, created_at: "2015-02-19 18:27:28", updated_at: "2015-02-19 18:27:28">
[2] pry(main)> Pet.create!(animals: 'cow')
ArgumentError: 'cow' is not a valid animals
from /home/arup/.rvm/gems/ruby-2.1.2@app/gems/activerecord-4.1.1/lib/active_record/enum.rb:103:in 'block (3 levels) in enum'
[3] pry(main)> Pet.animals
=> {"dog"=>0, "cat"=>1}
[5] pry(main)> Pet.first.dog?
  Pet Load (0.8ms)  SELECT  "pets".* FROM "pets"   ORDER BY "pets"."id" ASC LIMIT 1
=> false
[6] pry(main)> Pet.first.cat?
  Pet Load (0.7ms)  SELECT  "pets".* FROM "pets"   ORDER BY "pets"."id" ASC LIMIT 1
=> true
[7] pry(main)> Pet.first.cow?
  Pet Load (0.7ms)  SELECT  "pets".* FROM "pets"   ORDER BY "pets"."id" ASC LIMIT 1
NoMethodError: undefined method 'cow?' for #<Pet:0xbf8455c>
from /home/arup/.rvm/gems/ruby-2.1.2@app/gems/activemodel-4.1.1/lib/active_model/attribute_methods.rb:435:in `method_missing'
[8] pry(main)>

Pet.create!(animals: 'cow') 抛出错误,确认 Pet 模型不接受除 enum 值以外的任何值。