gpt4 book ai didi

ruby-on-rails - 如何限制列的值

转载 作者:行者123 更新时间:2023-12-04 00:11:57 25 4
gpt4 key购买 nike

我想限制一个字段的可用值。因此该列的值必须来自指定的一组值。是否可以使用迁移/模型?或者我必须在我的数据库中手动完成?

最佳答案

您将为此使用验证。有a whole Rails guide on the topic .在这种情况下,您要寻找的特定助手是 :inclusion ,例如:

class Person < ActiveRecord::Base
validates :relationship_status,
:inclusion => { :in => [ 'Single', 'Married', 'Divorced', 'Other' ],
:message => "%{value} is not a valid relationship status" }
end

2015 年 8 月编辑:从 Rails 4.1 开始,您可以使用 enum类方法。它要求您的列是整数类型:
class Person < ActiveRecord::Base
enum relationship_status: [ :single, :married, :divorced, :other ]
end

它也会自动为您定义一些方便的方法:
p = Person.new(relationship_status: :married)

p.married? # => true
p.single? # => false

p.single!
p.single? # => true

您可以阅读 enum 的文档。这里: http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html

关于ruby-on-rails - 如何限制列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com