我正在使用Rails构建一个事件应用程序,并在事件显示页面的底部有一个注释部分。我希望用户能够创建/更新(编辑)/delete,而只保留在同一个显示页面上的自己的评论。我该怎么做?
我把一些代码放在一起,但我对rails相当陌生,我的代码试图将用户从显示页面中移开,创建一个“注释”显示页面,而不是仅仅编辑events显示页面上的表单。我有正确的模型关联有_ and / routes,我的注释嵌套在我的事件路径中。到目前为止这是我的密码-
Comments_controller.rb
class CommentsController < ApplicationController
def create
@event = Event.find(params[:event_id])
@comment = @event.comments.create(params[:comment].permit(:user_id, :body))
redirect_to event_path(@event)
end
def show
@comment = Comment.find(params[:id])
@comment = @event.comments.find(params[:id])
end
def edit
@comment.user = current_user
end
def update
if @comment.update(comment_params)
redirect_to event_path(@event)
else
render 'edit'
end
end
def destroy
@event = Event.find(params[:event_id])
@comment = @event.comments.find(params[:id])
@comment.destroy
redirect_to event_path(@event)
end
private
def comment_params
params.require(:comment).permit(:body, :event_id, :user_id)
end
endEvent.show.erb
# some code for Events show...
# Comments code -
<% if user_signed_in? %>
<div id="comments">
<%= render 'comments/form', commentable: @event %>
<% if @event.comments.any? %>
<h2><%= @event.comments.size %> Comment</h2>
<%= render @event.comments %>
<% else %>
<h2>There are no comments yet</h2>
<% end %>
</div>
<% end %>Comments._comment.html.erb
<div class="comment clearfix">
<div class="comment_content">
<p class="comment_user"><strong><%= comment.user %></strong></p>
<p class="comment_body"><%= comment.body %></p>
<p class="comment_time"><%= time_ago_in_words(comment.created_at) %> Ago</p>
</div>
<% if user_signed_in? and current_user %>
<p><%= link_to 'Delete', [comment.event, comment],
method: :delete,
class: "button",
data: { confirm: 'Are you sure?' } %></p>
<p><%= link_to 'Edit', [comment.event, comment] %> </p>
<% end %>
</div>comments_form.html.erb
<%= simple_form_for([commentable, Comment.new ]) do |f| %>
<%= f.label :comment, label: 'Add a comment' %><br>
<%= f.text_area :body %><br>
<br>
<%= f.button :submit, "Create", class: "btn btn-primary" %>
<% end %>发布于 2017-02-16 13:33:36
要在同一页面上执行这些操作,需要将remote: true添加到表单中并通过JS提交。您可以在Rails/JS文档中更多地了解这一点。rails.html比,标准的rails方式是引导您到另一条路线。要禁止这样做,并在同一个视图页面上执行所有操作,您可以使用JS。
要将操作限制到当前用户,需要确保注释属于current_user。如果是user_signed_in呢?和comment.user_id == current_user.id (以防上面的代码无法防弹)。)
https://stackoverflow.com/questions/42274569
复制相似问题