How do I set a default value in rails active record based on two other values in the active record?

446 views Asked by At

My users are (booleans) students, tutors, or 'both'. My users are automatically false on all 3 unless specified, but I want the default value of 'both' to be based on a user being both a student and a tutor, therefore if student and tutor are booleans, both = student && tutor. How can I create a migration to do this?

Migration file that did not work.

class ChangeUserBoth < ActiveRecord::Migration
  def change
change_column :users, :both, :boolean, :default => :student && :tutor
  end
end
1

There are 1 answers

2
Arslan Ali On

You can't pass a conditional method in while writing your migration code, but you can achieve the desired result through the following way:

# In your model code    
before_save :set_both_based_on_student_and_tutor

private
def set_both_based_on_student_and_tutor
  # Ternary way saves your form 'both' being 'nil'. It would always 
  # either be true or false
  self.both = (self.student && self.tutor) ? true : false
end