27

What is the simplest way to make a field required in Rails?

inquiry.rb:

class Inquiry < ActiveRecord::Base
  attr_accessible :address, :email_id, :gender, :message, :mobile_number, :name
end
4

2 回答 2

47

You can use the presence validator:

validates :name, :presence => true
于 2013-08-23T08:36:18.007 回答
9

attr_accessible specifies 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.

So, if you want to make the attribute presence mandatory, you have to use a validation in your model, like this one:

validates :name, :presence => true
于 2013-08-23T09:37:04.497 回答