Ruby on rails 仅允许属性的特定单词

Ruby on rails 仅允许属性的特定单词,ruby-on-rails,activerecord,attributes,Ruby On Rails,Activerecord,Attributes,如何将字符串字段中允许的字符串限制为特定的单词 示例:我有一个模型属性animal:string,我想专门接受[dog、cat、bird、fish]。其他任何事情都会使对象无效。您可以在表单中使用选择字段,并将其写入模型中: module Animal dog = 1 cat = 2 bird = 3 fish = 4 end 及以旅游形式: <%= f.select :animal, { "dog" => 1, "cat" => 2, "b

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


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

您可以在表单中使用选择字段,并将其写入模型中:

module Animal
    dog = 1
    cat = 2
    bird = 3
    fish = 4
end
及以旅游形式:

<%= f.select  :animal, { "dog" => 1, "cat" => 2, "bird" => 3, "fish" => 4} %>
向模型中添加验证:

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

正如我所说,我将使用Rails功能

经过考验:


宠物。创造!动物:“cow”抛出错误,这确认了Pet模型不会接受除枚举值以外的任何内容。

您可以以其他方式使用Rails。这也和我说的有关,它们是完全不同的两件事。ActiveRecord枚举允许您将值映射到要存储在数据库中的整数,而验证确保一组值中只有一个是有效的。@softcode无问题。。。干杯!!:-知道几种方法总是很有趣的。
class ModelName < ActiveRecord::Base
  enum animals: %w(dog cat)
  # ...
end
# 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)>