# Advice on using define\_method in ActiveRecord descendant

**URL:** <https://www.ruby-forum.com/t/advice-on-using-define-method-in-activerecord-descendant/69689>\
**Category:** Ruby\
**Created:** [September 23, 2006, 12:05am UTC](https://www.ruby-forum.com/t/advice-on-using-define-method-in-activerecord-descendant/69689 "2006-09-23T00:05:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [September 23, 2006, 12:05am UTC](https://www.ruby-forum.com/t/advice-on-using-define-method-in-activerecord-descendant/69689/1 "2006-09-23T00:05:16Z")

</div>

All,

I have five accessor methods in an AR descendant that are virtually the  
same. I wanted to try and use define\_method to auto-define all five  
methods, but I can’t seem to get it to work.

Here are the methods:

def gross\_receipts=(new\_value)  
write\_attribute(:gross\_receipts, new\_value.to\_s.gsub(/,/, ‘’))  
end

def number\_of\_owners=(new\_value)  
write\_attribute(:number\_of\_owners, new\_value.to\_s.gsub(/,/, ‘’))  
end

def annual\_employee\_payroll=(new\_value)  
write\_attribute(:annual\_employee\_payroll, new\_value.to\_s.gsub(/,/,  
‘’))  
end

def uninsured\_subcontractors\_contract\_cost=(new\_value)  
write\_attribute(:uninsured\_subcontractors\_contract\_cost,  
new\_value.to\_s.gsub(/,/, ‘’))  
end

def insured\_subcontractors\_contract\_cost=(new\_value)  
write\_attribute(:insured\_subcontractors\_contract\_cost,  
new\_value.to\_s.gsub(/,/, ‘’))  
end

and here is what I tried to do to auto-create them:

for attr in [ :gross\_receipts, :number\_of\_owners,  
:annual\_employee\_payroll, :uninsured\_subcontractors\_contract\_cost,  
:insured\_subcontractors\_contract\_cost ] do  
self.class\_eval do  
define\_method("#{attr.to\_s}=(new\_value)") {  
write\_attribute(attr, new\_value.to\_s.gsub(/,/, ‘’))  
}  
end  
end

The for loop is syntactically correct, but these methods do not exist if  
I create a new instance of this object.

Is it because these methods don’t exist in the first place (they’re  
auto-created by ActiveRecord anyway)?

What am I doing wrong?

Thanks,  
Wes
