7步给商品添加评论功能

Published on:

既然是购物网站,那么用户评论功能必不可少。

下面我用详细的步骤来说明一下如何实现这个功能。

step1: rails g scaffold
$ rails g scaffold comment product_id:integer:index body:text user:references --skip-stylesheets
$ rake db:migrate

step2. create connection

+ has_many :comments
+ belongs_to :product
validates :body, presence: true

step3. add routes

-   resources :comments
 resources :products do
 +    resources :comments
 end

step4. revise comment create function

class CommentsController < ApplicationController

  before_action :authenticate_user!, only: [:create, :destroy]



  # POST /comments
  # POST /comments.json
  def create
    @product = Product.find(params[:product_id])
    @comment = @product.comments.new(comment_params)
    @comment.user = current_user

    if @comment.save
      redirect_to product_path(@product), notice: 'Review was successfully created!'
    else
      redirect_to product_path(@product), alert: "Comment can't be blank!"
    end
  end


  # DELETE /comments/1
  # DELETE /comments/1.json
  def destroy
    @product = Product.find(params[:product_id])
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_to product_path(@product), alert: "You have deleted the comment successfully"
  end

  private


    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:product_id, :body, :user_id)
    end
end

step5. revise product/show page

<h3 class="comments_title">
      <%= @product.comments.count %> Comments
    </h3>
    <hr>
    <div id="comments">
      <%= render @product.comments%>
      <%= render "comments/form"%>
    </div>

step6. touch app/views/comments/_comment.html.erb

div class="comments_wrapper clearfix">
        <div class="pull-left">
            <p class="lead"><%= comment.body %></p>
            <p><small>Submitted <strong><%= time_ago_in_words(comment.created_at) %> ago</strong> by <%= comment.user.name %></small></p>
        </div>

        <div class="btn btn-group btn-default pull-right">
            <% if comment.user == current_user -%>
                <%= link_to 'Delete', product_comment_path(@product, comment), method: :delete, data: { confirm: 'Are you sure?' } %>
            <% end %>
        </div>
    </div>

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

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

  <div class="field">
      <%= f.text_area :body, class: "form-control" %>
  </div>
  <%= f.submit "Add a comment", class: "btn btn-primary" %>
<% end %>

通过这七个步骤,就可以实现评论功能了。

http://forum.qzy.camp/uploads/qzy/original/2X/3/3c316b91aaf32e59443ce0cc4848fc8101375a07.png

最后,如果这个建议帮助了你的话,不妨给我们的作品投个票吧:
https://fullstack.xinshengdaxue.com/works/208

Comments

comments powered by Disqus