Forum: Ruby on Rails Validating a required relationship.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Gavin M. (Guest)
on 2006-05-23 13:46
(Received via mailing list)

I'm not sure if I'm missing something blindingly obvious here.

All the relationships that Rails comes with assume 0..n, yes?  It's
not a strict 1 to 1 or 1 to n because it's optional.  My question is
this -

What is the best way to implement a required relationship?

For example, if I require that a comment is made by a user (a user
has many comments, a comment has one user).  Is it enough to say in
the comment model

    validates_presence_of :user_id

or is there another, more rails-y way of doing this?

Daniel -. (Guest)
on 2006-05-23 14:35
(Received via mailing list)

There are two lines that you need in the comment model.  Rather than
a comment has_one user, it belongs_to a user.  The difference is that
foreign key is located in the comment table.

belongs_to :user
validates_presence_of :user

By declaring the symbol :user in these method calls, Active Record
automatically finds the class User and the field in the comments table
user_id and maps these rules that that field.

The belongs_to method works hand in hand with the has_many and has_one
methods in the corresponding models.  Basically, if the model has a
key field in it's table, then in needs a belong to.  Your not
constrianed to
only use the user_id field name for user.  You can tell AR to map a
key to any field.

ie for projects you may have fields in the table (to map to a user

in the project model

belongs_to :creator, :foreign_key => "created_by", :class_name => "User"
belongs_to :project_manager, :foreign_key => "project_manager_id",
:class_name => "User"

in the user model

has_many :project_managements, :class_name => "Project", :foreign_key =>
has_many :created_projects, :class_name => "Project", :foreign_key =>

There are a number of options for both of these method calls that can be
found in the docs.

Hopefully this helps.
This topic is locked and can not be replied to.