dagda1
dagda1

Reputation: 28790

Accessing a RoR ActiveRecord's attributes from within the ActiveRecord instance

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?

Upvotes: 1

Views: 3343

Answers (2)

Dave Sims
Dave Sims

Reputation: 5128

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.

Upvotes: 3

Shadwell
Shadwell

Reputation: 34774

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

Upvotes: 0

Related Questions