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
on 2006-05-23 13:46
on 2006-05-23 14:35
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.