Reputation: 133
Sorry, y'all. New to Ruby on Rails.
I am updating a profile form that consists of the following YES/NO questions:
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
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
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
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