实现评论功能

Published on:

step1 :rails g model review product_id:integer user_id:integer body:text

rake db:migrate

step2: 修改model

user.rb / product.rb :
has_many :reviews

review.rb
belongs_to :user
belongs_to :product
validates :body, presence: true

step3: 增加routes

resources :products do
resources :reviews
end

step4: rails g controller reviews

class ReviewsController < ApplicationController
  before_action :authenticate_user!, only: [:create, :destroy]
  def create
    @product = Product.find(params[:product_id])
    @review = @product.reviews.new(review_params)
    @review.user = current_user

   if @review.save
  redirect_to product_path(@product), notice: 'Review was successfully created.'
else
  redirect_to product_path(@product), notice: 'You have to write some words.'
end
  end

  def destroy
    @product = Product.find(params[:product_id])
    @review = Review.find(params[:id])
    @review.destroy
    redirect_to product_path(@product), alert: "You have deleted the review successfully"
  end

  private
  def review_params
    params.require(:review).permit(:body)
  end
end

step5 : 产品 show 页面添加:

 <div class="row review">
  <div class="col-sm-10 col-sm-offset-1">
    <h3 class="reviews_title">
      <%= @product.reviews.count %> Reviews
    </h3>
    <hr>
    <div id="reivews">
      <%= render @product.reviews%>
      <hr>
      <%= render "reviews/form"%>
    </div>
  </div>
</div>

step6. touch app/views/reviews/_review.html.erb

 <div class="reviews_wrapper clearfix">
    <div class="pull-left">
        <p class="lead"><%= review.body %></p>
        <p>
            <small>Submitted
                <strong><%= time_ago_in_words(review.created_at) %>
                    ago</strong>
                by
                <%= review.user.email %></small>
        </p>
    </div>
    <div>
<% if review.user == current_user %>
   <%= link_to("Delete", product_review_path(@product, review), method: :delete, data: { confirm: "Are you sure?"}, class: "btn btn-sm pull-right") %>
<% end %>
  </div>
</div>

step7 . touch app/views/reviews/_form.html.erb

<%= simple_form_for([@product, @product.reviews.build]) do |f|%>

  <div class="field">
      <%= f.text_area :body, class: "form-control" %>
  </div>


  <%= f.submit "Add a Review", class: "btn btn-primary" %>
<% end %>

Comments

comments powered by Disqus