如何增加评论功能

Published on:

如何给工作添加评(吐)论(槽)功能

这工作这么奇葩,还没地方吐槽,简直不让人活了!这年头,没个吐槽功能,你还好意思说自己是网站?

现在就教你如何做出一个吐槽功能。

刚做完rails101你会不会想用 group post来套用呢?先别急着动手,还记不记得你的第一个专案——rails初级练习?topic啊,title啊,vote啊巴拉巴拉......用scaffold做的比rails101简单一万倍好么!请用简单的方法最迅速的完成功能,直线前进!

step1.终端输入

rails g scaffold comment job_id:ingeger:index body:text user:reference

我们的吐槽功能的CRUD就建好了,名字叫commit,我们要有job_id(类似于title)、body(类似于description)、user(需要记录是谁吐的槽,要不生气了去套谁麻袋,套上麻袋就是一顿揍,揍完就跑,他都不知道是谁打的,扯远了)。
终端运行,

rake db:migrate

step2.修改路由routes
config/routes

resouces :jobs do
 resources :comments
end

ps:如果你增加过其他功能,resources :jobs do 下面可能还会有其他的东西,resumes之类的,请保证resources仅在resources :jobs do与end之间。

step3.model
model/job.rb
has_many :comments
model/comment.rb
belongs_to :job

step4.更改controller

class CommentsController < ApplicationController

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



  # POST /comments
  # POST /comments.json
  def create
    @job = Job.find(params[:job_id])
    @comment = @job.comments.new(comment_params)
    @comment.user = current_user

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


  # DELETE /comments/1
  # DELETE /comments/1.json
  def destroy
    @job = Job.find(params[:job_id])
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_to job_path(@job), alert: "You have deleted the comment successfully"
  end

其他的我们都用不到,直接删去就行了。

step5.html
首先是修改views/jobs/show.html.erb

  <h2 class="comments_title">
    <%= @job.comments.count %> Comments
  </h2>
  <hr>
  <div id="comments">

    <%= render @job.comments%>
  </br>
    
 </div>

接着终端输入:
touch app/views/comments/_comment.html.erb
加入:

  <div class="container">
  <div class="row">
<div class="col-md-6 col-centered">

  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title"><%= @job.title%></h3>
    </div>
    <div class="panel-body">
      <p><%= simple_format(@job.description) %></p>
      <div class="text-center">
        <%= link_to("交出bug细节,以便领走", new_job_resume_path(@job), :style => "font-size: 30px; text-decoration:underline;") %>
      </div>
    </div>
  </div>

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

    <%= render @job.comments%>
  </br>
    <%= simple_form_for([@job, @job.comments.build]) do |f|%>
      <div class="field">
        <%= f.text_area :body, class: "form-control" %>
      </div>
      <%= f.submit "submit", class: "btn btn-primary" %>
    <% end %> 
  </div>
</div>
  </div>
</div>

ok,ddb rroutes mmodel ccontroller vview 全部修改完毕,这给我牛b的,叉会腰。
css的内容我就不献丑了,请大家随意自便。

就酱,有什么问题 欢迎随时和我联系,微信号:m60_06m

参考
1.Rails第二课:初级联系
2.7步给商品添加评论功能

Comments

comments powered by Disqus