Rails foundationSort Order

Rails: One to Many Relationships

In this episode we discus one-to-many relationships. We show you how to create a migration for a comment model that belongs to a post.

Generating the Comment Model

rails g model comment body:text post:references

We will get a new comment model

# app/models/comment.rbclass Comment < ActiveRecord::Base  belongs_to :postend

We also get a migration file that looks something like this

class CreateComments < ActiveRecord::Migration  def change    create_table :comments do |t|      t.text :body      t.references :post, index: true, foreign_key: true            t.timestamps, null: false    end  endend

To actually modify our database we need to run the migration command

rails db:migrate

We also need to tell the Post model about it's children

# app/models/post.rbclass Post < ActiveRecord::Base  has_many :commentsend

Boot up Rails Console and Let's Play

rails c# load our postpost = Post.first# lets create a commentcomment = post.comments.build

At this point we have a comment in memory and it is associated with our post however the record doesn't exist in the database yet, to commit the object to the database we need to save our comment

# this will persist our comment to the databasecomment.save# we can destroy the comment comment.destroy

Lets try and create a comment with an actual body.

comment = post.comments.build(body: "First!")comment.save# we can also create the comment in 1 shotpost.comments.create(body: "Second")

We can load the comments for the particular post by using


Updating our Views

In our view we can display the comments count for each of the post

# app/views/posts/_post.html.erb<p>  Comments(<%= post.comments.count %>)</p>

In our post show page we can even render out the comments section!

# app/views/posts/show.html.erb# ...<hr><h2>Comments</h2><% @post.comments.each do |c| %> <div class='panel panel-default'>   <div class='panel-body'>     <%= comment.body %>   </div> </div><% end %>