Forum: Ruby on Rails verifying best practice

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
44c645f2c3a008972d9904102bae09df?d=identicon&s=25 matthew collins (Guest)
on 2006-02-18 17:55
(Received via mailing list)
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.
D8cb8c8cd40ddf0cd05241443a591868?d=identicon&s=25 Duane Johnson (Guest)
on 2006-02-18 18:53
(Received via mailing list)
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 Johnson
(canadaduane)
http://blog.inquirylabs.com/
59de94a56fd2c198f33d9515d1c05961?d=identicon&s=25 Tom Mornini (Guest)
on 2006-02-18 21:10
(Received via mailing list)
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 Mornini
1e99128ebac5ca41c91940291d315332?d=identicon&s=25 Luke Redpath (Guest)
on 2006-02-19 03:01
(Received via mailing list)
Even better (again assuming the presence of a loaded user object):

@project = @user.project.build( params[:project] )
@project.save
1e99128ebac5ca41c91940291d315332?d=identicon&s=25 Luke Redpath (Guest)
on 2006-02-19 03:01
(Received via mailing list)
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] )
This topic is locked and can not be replied to.