【发布时间】:2018-11-29 02:28:07
【问题描述】:
我正在构建一个用于练习的应用程序(Instagram 副本),但我很难让某个功能发挥作用。
我想要发生的是,用户能够编辑或删除他们自己关于图片的 cmets。我能够使删除功能起作用,但我无法弄清楚“编辑评论”功能。我希望用户能够从图片显示页面中编辑评论。代码如下。
pics_controller.rb
class PicsController < ApplicationController
before_action :find_pic, only: [:show, :edit, :update, :destroy, :upvote]
before_action :authenticate_user!, except: [:index, :show]
before_action :require_same_user, only: [:edit, :update, :destroy]
def index
@pics = Pic.all.order("created_at DESC")
end
def show
end
def new
@pic = current_user.pics.build
end
def create
@pic = current_user.pics.build(pic_params)
if @pic.save
redirect_to @pic, notice: "Your pic has been posted!"
else
render :new
end
end
def edit
end
def update
if @pic.update(pic_params)
redirect_to @pic, notice: "Awesome! Your Pic was updated!"
else
render :edit
end
end
def destroy
if @pic.destroy
redirect_to root_path
end
end
def upvote
@pic.upvote_by current_user
redirect_back fallback_location: root_path
end
private
def pic_params
params.require(:pic).permit(:title, :description, :image)
end
def find_pic
@pic = Pic.find(params[:id])
end
def require_same_user
if current_user != @pic.user
flash[:danger] = "You can only edit or delete your own pictures"
redirect_to root_path
end
end
end
cmets_controller.rb
class CommentsController < ApplicationController
def create
@pic = Pic.find(params[:pic_id])
@comment = @pic.comments.create(params[:comment].permit(:name, :body))
redirect_to pic_path(@pic)
end
def edit
@pic = Pic.find(params[:pic_id])
@comment = @pic.comments.find(params[:id])
redirect_to @pic
end
def update
@comment = @pic.comments.find(params[:id])
@comment.update_attributes(comment_params)
if @comment.save
redirect_to @pic
end
end
def destroy
@pic = Pic.find(params[:pic_id])
@comment = @pic.comments.find(params[:id])
@comment.destroy
redirect_to pic_path(@pic)
end
def show
@pic = Pic.find(params[:pic_id])
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
这是从显示页面调用的 (_comment.html.erb) 部分
<div class="card" style="width: 18rem;">
<div class="card-header">
<span class="badge badge-dark"><%= comment.name %></span>
</div>
<ul class="list-group list-group-flush">
<p><%= comment.body %></p>
</ul>
</div>
<% if user_signed_in? && comment[:body].present? %>
<p><%= link_to 'Delete Comment', [comment.pic, comment], method: :delete, class: "btn btn-danger",
data: { confirm: "Are you sure?" } %></p>
<p><%= link_to 'Edit Comment', edit_pic_comment_url(@pic, comment), class: 'btn btn-primary' %></p>
<% end %>
非常感谢任何帮助。 TIA
【问题讨论】:
-
那么错误是什么?
标签: ruby-on-rails ruby redirect model-view-controller