Search code examples
ruby-on-rails-3activemodel

How to iterate over all "table columns" in an ActiveModel?


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.


Solution

  • 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.