Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict values for a column

I want to restrict available values for a field. So the value of the column must be from specified set of values. Is it possible using migration/models? Or I have to do it manually in my DB?

like image 789
Konstantin Milyutin Avatar asked Nov 10 '11 21:11

Konstantin Milyutin


People also ask

How do I restrict columns in Excel?

Go to the Protection tab and uncheck Locked option and click Ok. Now select only the cells or columns, rows that you want to protect. Right click and choose Format cells again. Go to the protection tab and check Locked option and click Ok.

How do I lock a cell to a specific value in Excel?

Select the cells you want to lock. On the Home tab, in the Alignment group, click the small arrow to open the Format Cells popup window. On the Protection tab, select the Locked check box, and then click OK to close the popup.


2 Answers

You'll use validations for this. There's a whole Rails guide on the topic. The specific helper you're looking for in this case is :inclusion, e.g.:

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

Edit Aug. 2015: As of Rails 4.1, you can use the enum class method for this. It requires that your column be an integer type:

class Person < ActiveRecord::Base
  enum relationship_status: [ :single, :married, :divorced, :other ]
end

It automatically defines some handy methods for you, too:

p = Person.new(relationship_status: :married)

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

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

You can read the documentation for enum here: http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html

like image 109
Jordan Running Avatar answered Sep 19 '22 18:09

Jordan Running


It depends on the amount of confidence you need. You could just add a validator to your model to restrict it to those values but then you wont be sure that existing data will match (and will cause subsequent saves to fail because of validation) and also that other changes could be made by other apps/raw sql that would get around it.

If you want absolute confidence, use the database.

Here's what you might want to use if you do it in the database (which is quite limited compared to what a rails validator could do: http://www.w3schools.com/sql/sql_check.asp

like image 37
Ponny Avatar answered Sep 20 '22 18:09

Ponny