Migrations-looping through add_column lines


#1

Hi All,

Hoping this is an easy question… Can I loop through add_columns?

I’ve got a bunch of columns that I need to add to a table… I don’t
really want to type “add_column” 30 times… and then “remove_column”
another 30 times

Is there an easy way to just loop through the is so my migration doesn’t
look like this?:

def self.up

add_column :enrollments, :fname
add_column :enrollments, :lname
add_column :enrollments, :email, :string
add_column :enrollments, :school_type, :string
add_column :enrollments, :number_of_students, :string


add_column :enrollments, :school_name, :string
add_column :enrollments, :internet, :boolean
add_column :enrollments, :internet_quality, :string
#(and on and on and on.....)

end

def self.down

remove_column :enrollments, :fname
remove_column :enrollments, :lname
remove_column :enrollments, :email
remove_column :enrollments, :school_type
remove_column :enrollments, :number_of_students


remove_column :enrollments, :school_name
remove_column :enrollments, :internet
remove_column :enrollments, :internet_quality
#blah blah blah...

end

Thanks!


#2

sure you could do that, but the problem is that most likely your
columns are going to have more differences than just the name of the
column, so you’d have to structure your loops around you individual
columns…when its all said and done, it would most likely have just
been easier to spell each one out. not only that, but the method that
everyone tends to use is very readable.

ex:

all same type, easy enough

[:name, :description, :location].each do |col|
add_column col, :string
end

now try that when all your columns are different types, lengths, not
null, unique, have default values, etc…not so easy now.