仅允许属性的特定单词

时间:2015-02-18 06:03:42

标签: ruby-on-rails activerecord attributes

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

示例:我有一个模型属性animal:string,我想独家接受["dog", "cat", "bird", "fish"]。其他任何事情都会使对象无效。

3 个答案:

答案 0 :(得分:2)

为您的模型添加inclusion验证:

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

答案 1 :(得分:2)

正如我所说,我会使用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 ($1, $2, $3) 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模型除枚举值之外不接受任何其他内容。

答案 2 :(得分:0)

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

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

并以巡回形式:

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