Forum: Ruby on Rails Validating a required relationship.

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.
82da8756017e461cf1e6c3d9f85e59a1?d=identicon&s=25 Gavin Montague (Guest)
on 2006-05-23 11:46
(Received via mailing list)
Hello,

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?

Thanks,
	Gavin
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2006-05-23 12:35
(Received via mailing list)
Gavin,

There are two lines that you need in the comment model.  Rather than
saying
a comment has_one user, it belongs_to a user.  The difference is that
the
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
foreign
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
foreign
key to any field.

ie for projects you may have fields in the table (to map to a user
record)
created_by
project_manager_id

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 =>
"project_manager_id"
has_many :created_projects, :class_name => "Project", :foreign_key =>
"created_by"

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.