views:

30

answers:

2

Hi,

I am confused about how to access the attributes of an ActiveRecord instance from a method within the ActiveRecord instance.

For example I have a Lead class that inherits from ActiveRecord:

class Lead < ActiveRecord::Base
end

I have the following scaled down migration file that shows the columns of an ActiveRecord table:

class CreateLeads < ActiveRecord::Migration
  def self.up
    create_table :leads do |t|
      t.string :phone_1
      t.string :phone_2
      t.string :web
      t.string :fax
      t.timestamps
    end
  end
  def self.down
    drop_table :leads
  end
end

I am using send in a method of the Lead class to set these attributes internally like this:

def instance_method(prop)
  self.send("#{prop}=".to_sym, value_node.text) 
end

The question I have is how do I access these :phone_1, :phone_2 attributes when within the ActiveRecord instance itself without having to use send which is the only way I can think of. I think these attributes are accessed via method_missing when accessing them from the public interface like this:

puts lead.phone_1

But I have no idea how to access them from within the ActiveRecord instance apart from via send.

Is it possible?

Thanks

Paul

A: 

You can just use self.phone1 or self.phone2/ For example:

class Lead < ActiveRecord::Base

  def some_instance_method
    self.phone1 = '1234567'
    self.phone2 = self.phone1
  end

end
Shadwell
+1  A: 

You can reference AR attributes directly from within any AR instance. No need for any 'send' magic:

def some_method
 self.some_attribute='value' # with or without self
 x = some_attribute
end

What lead you to believe otherwise?

If you need to bypass AR's built in accessors you can use read_attribute and write_attribute.

Dave Sims
its been a long day. I think I need to put the laptop away :-)
dagda1
You and me both brother. Walking out now...
Dave Sims