Forum: Ruby on Rails Migrations-looping through add_column lines

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dustin A. (Guest)
on 2007-07-13 01:32
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!
Chris H. (Guest)
on 2007-07-13 01:50
(Received via mailing list)
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.
This topic is locked and can not be replied to.