About ruby on rails, hackintosh, iphone3g and etc.

Thursday, January 22, 2009

Using id after update/create command for rails

In rails, there is a useful method as to capture the id of a record upon successful creation of the record in database.
Example code:

@contact = Contact.new(params[:contact])

respond_to do |format|
if @contact.save

Listing above shows typical execution of creating a row in rails model. Upon save, rails will automatically populate the @contact class with the id generated from database. (@contact.id)

So we can continue to use the following:

@contact = Contact.new(params[:contact])

respond_to do |format|
if @contact.save
#create empty contact details with only contact id
@contact_details = ContactDetails.new()
@contact_details.contact_id = @contact.id
@contact_details.save

@contact.id can be used to populate foreign key of @contact_details.

No comments: