Step 1.建立收藏的 model
执行rails g model favorite
db/migrate/20170614122223_create_favorites.rb
class CreateFavorites < ActiveRecord::Migration[5.0]
def change
create_table :favorites do |t|
t.integer :product_id
t.integer :user_id
t.timestamps
end
end
end
Step 2.建立关联
app/models/favorite.rb
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :product
end
app/models/product.rb
- has_many :reviews
+ has_many :reviews, dependent: :destroy
+ has_many :favorites
+ has_many :fans, :through => :favorites, :source => :user
acts_as_votable
app/models/user.rb
has_many :orders
- has_many :reviews
+ has_many :reviews, dependent: :destroy
+ has_many :favorites
+ has_many :favorite_products, :through => :favorites, :source => :product
+ def is_fan_of?(group)
+ favorite_products.include?(group)
+ end
Step 3.建立收藏的 controller
执行rails g controller favorites
并修改
app/controllers/favorites_controller.rb
class FavoritesController < ApplicationController
def index
@products = current_user.favorite_products
end
end
app/controllers/products_controller.rb
def favorite
@product = Product.find(params[:id])
current_user.favorite_products << @product
flash[:notice] = "您已收藏宝贝"
redirect_to :back
end
def unfavorite
@product = Product.find(params[:id])
current_user.favorite_products.delete(@product)
flash[:notice] = "您已取消收藏宝贝"
redirect_to :back
end
Step 4.增加相应的路由
config/routes.rb
+ resources :favorites
resources :products do
member do
post :add_to_cart
+ post :favorite
+ post :unfavorite
put "like", to: "products#upvote"
put "dislike", to: "products#downvote"
end
resources :reviews
end
Step 5.修改app/views/product/show.html.erb
app/views/products/show.html.erb
<div class="col-md-2" >
<% if current_user %>
<% if !current_user.is_fan_of?(@product) %>
<%= link_to favorite_product_path(@product), :class => "like btn btn-default", method: :post do %>
<i class="fa fa-heart fa-lg"></i>
<% end %>
<% else %>
<%= link_to unfavorite_product_path(@product), :class => "unlike btn btn-default", method: :post do %>
<i class="fa fa-heart fa-lg"></i>
<% end %>
<% end %>
<% else %>
<%= link_to favorite_product_path(@product), :class => "like btn btn-default",method: :post do %>
<i class="fa fa-heart fa-lg"></i>
<% end %>
<% end %>
</div>
</div>
<div class="row share">
<hr />
<div class="col-md-6">
<p> 收藏人气(<%= @product.fans.count %>) </p>
</div>
<div class="col-md-6">
<%= link_to like_product_path(@product), method: :put do %>
<div class="pi-thumbs-up">
点赞(<%= @product.get_upvotes.size %>)
</div>
<% end %>
</div>
</div>
Step 6.建立收藏的 view
执行touch app/views/favorites/index.html.erb
app/views/favorites/index.html.erb
<% @products.each do |product|%>
<p><%= link_to(product.title, product_path(product)) %></p>
<p><%= product.description %></p>
<p><%= product.price %></p>
<% end %>
完成!