1

I want to iterate over all the columns in a table for a Model and perform some logic on it.

  def fetch_all_fields
    @profile_page ||= profile_page
    SOMETHING.each do |field_name|
      method_name = "remote_#{field_name}"
      if self.respond_to?(method_name, true)
        field_values[field_name] = send(method_name)
      end
    end
    field_values
  end

Basically, a simple loop in my model that allows me to define methods like remote_date_of_birth. This method then contains the correct logic and information to parse the date_of_birth from some remote dataset (it actually scrapes HTML).

The part that I cannot find, is how to get the "columns" for the table for this Model. Say a table profiles, that, in abovementioned example, has a column date_of_birth.

berkes
  • 26,996
  • 27
  • 115
  • 206

2 Answers2

4

The most obvious way is to use the columns method, for example:

> User.columns.each { |c| puts "#{c.name} - #{c.sql_type} - #{c.type}" }
id - INTEGER - integer
email - varchar(255) - string
crypted_password - varchar(255) - string
password_salt - varchar(255) - string
persistence_token - varchar(255) - string
login_count - integer - integer
failed_login_count - integer - integer
last_request_at - datetime - datetime
current_login_at - datetime - datetime
last_login_at - datetime - datetime
current_login_ip - varchar(255) - string
last_login_ip - varchar(255) - string
created_at - datetime - datetime
updated_at - datetime - datetime
nickname - varchar(255) - string
first_name - varchar(255) - string
last_name - varchar(255) - string

If you need them in an arbitrary, non-sorted order, the hash is more appropriate.

This does not include the associations, which can be found via the reflections method.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

Assuming that your model inherits from ActiveRecord, you can call column_names on your model's class. columns or columns_hash could also be used.

Note that these are class methods. If, for some reason, you don't want to use the class name directly, you can do something like obj.class.columns_hash.

Tomas Mattia
  • 371
  • 2
  • 7