Verifying best practice

i have a Project model, which belongs_to :user

when i add a project, the users_id is based on the session[:users_id].

to get the users_id into the projects table, i’m doing this:

@project = Project.new(params[:project])
@project.users_id = session[:users_id]

this is working, i’m just verifying this is the best way to do it.

On Feb 18, 2006, at 9:53 AM, matthew collins wrote:

Yup, that looks good, Matthew.

You may want to change “users_id” to “user_id”, however, since the
latter is the Rails naming convention and will make your belongs_to
and has_many associations work without specifiying a foreign_key.

Duane J.
(canadaduane)
http://blog.inquirylabs.com/

On Feb 18, 2006, at 8:53 AM, matthew collins wrote:

to get the users_id into the projects table, i’m doing this:

@project = Project.new(params[:project])
@project.users_id = session[:users_id]

this is working, i’m just verifying this is the best way to do it.

It’s more Rails idiomatic to let the associations handle the assignment,
and to use singular foreign key naming:

If you have a @user object around:

@project = Project.new(params[:project])
@project.user = @user


– Tom M.

Sorry, the above is assuming a has_one relationship between user and
project. If it is has_many, you want:

@project = @user.projects.build( params[:project] )

Even better (again assuming the presence of a loaded user object):

@project = @user.project.build( params[:project] )
@project.save