Ruby-on-rails 如何在 Rails 中创建所需的字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18398340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a field required in Rails?
提问by Loganayaki Palanisamy
What is the simplest way to make a field required in Rails?
在 Rails 中创建所需字段的最简单方法是什么?
inquiry.rb:
查询.rb:
class Inquiry < ActiveRecord::Base
attr_accessible :address, :email_id, :gender, :message, :mobile_number, :name
end
回答by Mischa
回答by tomasborrella
attr_accessiblespecifies a white list of model attributes that can be set via mass-assignment. This is meant to protect sensitive attributes from being overwritten by malicious users tampering with URLs or forms. It has nothing to do with validations.
attr_accessible指定可以通过批量分配设置的模型属性白名单。这是为了保护敏感属性不被恶意用户篡改 URL 或表单覆盖。它与验证无关。
So, if you want to make the attribute presence mandatory, you have to use a validationin your model, like this one:
因此,如果您想让属性存在强制性,则必须在模型中使用验证,如下所示:
validates :name, :presence => true

