# Setting an attribute when building or creating?

**URL:** <https://www.ruby-forum.com/t/setting-an-attribute-when-building-or-creating/113319>\
**Category:** Rails\
**Created:** [August 29, 2007, 8:01pm UTC](https://www.ruby-forum.com/t/setting-an-attribute-when-building-or-creating/113319 "2007-08-29T20:01:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [August 29, 2007, 8:01pm UTC](https://www.ruby-forum.com/t/setting-an-attribute-when-building-or-creating/113319/1 "2007-08-29T20:01:11Z")

</div>

I appreciate any help you can give me on this.

Say you have categories and products. Category has many products. So you  
do the following

c = Category.new  
p = c.products.build

p.category\_id is already set. Say you had an attribute called “key” for  
products. How would you get key to be automatically set to whatever you  
want when the product is built off of a category?

Thanks!

---

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [August 29, 2007, 9:30pm UTC](https://www.ruby-forum.com/t/setting-an-attribute-when-building-or-creating/113319/2 "2007-08-29T21:30:50Z")

</div>

Look into using callbacks, e.g. after\_create or before\_create (define  
the methods and they get fired as you’d expect)

You could check for the presence of the category id in such a  
callback, and then do your key stuff.

On Aug 29, 7:01 pm, Ben J. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
