Setting an attribute when building or creating?

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!

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. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs