$ rails g model Favourite post_id:integer
$ rake db:migrate
Step 2: Add one-to-many relationship into Models
In app/models/post.rb,
class Post < ActiveRecord::Base attr_accessible :body, :title, :author_id belongs_to :author has_many :comments has_many :favourites validates_presence_of :body, :title end
In app/models/favourite.rb,
class Favourite < ActiveRecord::Base attr_accessible :post_id belongs_to :post end
Step 3: Adding new methods into Posts Controller
In app/controllers/posts_controller.rb,
class PostsController < ApplicationController
before_filter :authenticate, :except => [ :index, :show ]
# ... all the action go in here
def add_favourite
post = Post.find(params[:post_id])
post.favourites.build(:post_id => params[:post_id])
if post.save
redirect_to post_path(post) #redirect_to action: :index
end
end
# the authentication action
end
Step 4: Connecting URLs to Code by Editing Routes Config
In config/routes.rb,
QuickBlog::Application.routes.draw do
resources :authors
resources :comments
get '/posts/add_favourite', to: 'posts#add_favourite'
resources :posts do
resources :comments, :only => [:create, :destroy]
end
end
Step 5: Edit the Views in Posts
In app/views/posts/show.html.erb,
<p id="notice"><%= notice %></p>
<%= render :partial => @post %>
by <%= @post.author.name %>
<br/>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
<p><%= link_to 'Add Favourite', "/posts/add_favourite?post_id=#{@post.id}" %> (<%= @post.favourites.size %>)</p>
Return to Internship Note (LoanStreet)
Previous Episode: Update Blog with Author
Next Episode: Update Blog with Favourites (Part 2)
0 comments:
Post a Comment