sbuck89
sbuck89

Reputation: 133

How can I change_column_default based on the value selected of another row in a Ruby on Rails migration?

Sorry, y'all. New to Ruby on Rails. I am updating a profile form that consists of the following YES/NO questions: enter image description here

The user table already has an existing children_under_five column but I'd like to add a column has_children to incorporate whether they have children at all. The only new field will be has_children which, in the event, someone has a child under 5 that means they have a child, so has_children should be true for those folks, otherwise it should default to false. How can I implement this within the migration itself? This is all I have so far:

  def change
    add_column :users, :has_children, :boolean, default: false, null: false
  end
end

Upvotes: 0

Views: 166

Answers (3)

muskrat_
muskrat_

Reputation: 101

How about using a method here?

class User < ApplicationRecord
  def has_children?
    self.children_under_five > 0 ? true : false
  end
end

And you can use it as

>> user = User.first
   user.has_children? # returns true or false

Upvotes: 0

dbugger
dbugger

Reputation: 16464

Add an update statement either in that migration or a following one...

 def change
   query = <<-SQL
     update users
     set has_children = children_under_five
   SQL

   execute query
 end

Upvotes: 2

Fernando rivas
Fernando rivas

Reputation: 84

I quite dont understand your question but the question is ? How to add a column with migration? well: rails g migration add_has_children_to_users has_children:boolean then rails db:migrate

Upvotes: -1

Related Questions