Wednesday, February 01, 2006

Passing an object to the block intialization autoamtically sets up association

If Obj A belongs_to Object B, then passing an object B in the block intialization of object B will automatically set up the database connections, i.e. user.note_id = note.id.

Consider a user.
class User < ActiveRecord::Base
....
belongs_to :note
end

A Note model
class Note < ActiveRecord::Base
end

The ddl is:
create_table users (
`id` int not null,
`note_id` int default NULL
)

create_table notes (
`id` int not null,
`note` text
)


Now consider the following code:

params[:user] contains intialization for the attributes of the user class.

params[:user][:note] = Note.new(:note => "ffo bar")
user = User.new(params[:user])

This will automatically insert the note into the database and then create the user record with note_id set to the id of this new note record.

0 Comments:

Post a Comment

<< Home