1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Rails Blog Tutorial - Allowing Comments


3 of 7

Setting up the Model

Once the database tables are in place, you can begin setting up the model. In the model, things like data validations--to ensure required fields are present--and relations can be defined. Two relations will be used.

A blog post has many comments. The has_many relationship doesn't require any special fields in the posts table, but comments table has a post_id to link it to the posts table. From Rails, you can say things like @post.comments to get a list of Comment objects that belong to the @post object. Comments are also dependent on their parent Post object. If the Post object is destroyed, all child comment objects should be destroyed as well.

A comment belongs to a post object. A comment can only be associated with a single blog post. The belongs_to relationship only requires a single post_id field to be in the comments table. To access a comment's parent post object, you can say something like @comment.post in Rails.

The following are the Post and Comment models. Several validations have been added to the comment model to ensure that users fill out the required fields. Note also the has_many and belongs_to relationships.

# File: app/models/post.rb
 class Post < ActiveRecord::Base
   has_many :comments, :dependent => :destroy
# File: app/models/comment.rb
 class Comment < ActiveRecord::Base
   belongs_to :post
   validates_presence_of :name
   validates_length_of :name, :within => 2..20
   validates_presence_of :body
  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. Setting up the Model

©2014 About.com. All rights reserved.