31

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
Mischa
  • 42,876
  • 8
  • 99
  • 111
  • Your question should show that you researched this topic prior to asking the community for an answer. We programmers/developers should be inquisitive and searching for the answers before asking for assistance. – Tass Oct 12 '15 at 19:34

2 Answers2

51

You can use the presence validator:

validates :name, :presence => true
Mischa
  • 42,876
  • 8
  • 99
  • 111
11

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
tomasborrella
  • 480
  • 2
  • 8