Topic: Ruby & ActiveRecord - Variable substitution to reference column names

Is there a way to use a variable to reference an ActiveRecord object as opposed to the explicit field/column name from the database table?  So, instead of mytable.fieldname, something like mytable.fieldvar.  Ideas?

What I have now:

=====
   log_entry = AstLog.new
   rami_event.each do |field|
     #Note to self:  Figure out how to change field[0] to the field reference
     case field[0].downcase
       when "event"
         log_entry.event = field[1]
       when "context"
         log_entry.context = field[1]
       when "extension"
         log_entry.extension = field[1]
       when "priority"
         log_entry.priority = field[1]
       when "application"
         log_entry.application = field[1]
     end
   end
   log_entry.save
=====

Would prefer something like:

=====
   log_entry = AstLog.new
   rami_event.each do |field|
     log_entry.field[0].downcase = field[1]
   end
   log_entry.save
=====

Last edited by muppetmaster (2007-04-28 11:17:13)

Re: Ruby & ActiveRecord - Variable substitution to reference column names

Try this:

rami_event.each do |field|
     log_entry[field[0].downcase] = field[1]
   end

ActiveRecord allows you to access fields similar to a hash. There's a few other ways to do this too. I can post those if you want.

Railscasts - Free Ruby on Rails Screencasts

Re: Ruby & ActiveRecord - Variable substitution to reference column names

That did the trick, thanks!  Also, did this for outputting:

===
class AstLog < ActiveRecord::Base
end

field_names = AstLog.column_names
log_rows = AstLog.find(:all)

cnt = 0
log_rows.each do |row|
  puts "--- Record " + cnt.to_s + " ---"
  field_names.each do |field_name|
    if row[field_name] != nil
      puts field_name + " == " + row[field_name].to_s
    end
  end
  puts " "
  cnt += 1
end
===

Works, but always open to recommendations to be more Ruby-esque.

Last edited by muppetmaster (2007-04-29 03:08:31)

Re: Ruby & ActiveRecord - Variable substitution to reference column names

There's a much better way to do this:

AstLog.find(:all).each_with_index do |ast_log, index|
  puts "--- Record #{index+1} ---"
  ast_log.attributes.each do |name, value|
    puts "#{name} == #{value}" unless value.nil?
  end
  puts " "
end

In this case I'm using the attributes method to fetch both the attribute names and values for the model.

However, I don't know what exactly you're trying to do here. Usually you shouldn't use "puts" in Rails. Instead use the logger:

logger.info "test"

But as I said, I don't know what you are doing here so it's hard to say the best way to go.

Railscasts - Free Ruby on Rails Screencasts

Re: Ruby & ActiveRecord - Variable substitution to reference column names

I will look into that.  This is only a Ruby script, as I would never put a puts in Rails.  wink