我正在使用Rails構建事件應用程序,並在事件顯示頁面的底部有註釋部分。我希望用戶能夠創建/更新(編輯)/刪除他們自己的評論,同時保留在同一個展示頁面上。我該怎麼做呢?Rails - 作爲部分編輯註釋
我已經把一些代碼放在一起,但我相當新的軌道和我的代碼試圖使用戶遠離顯示頁面,並創建一個'評論'顯示頁面,而不是隻編輯事件顯示頁。我有正確的模型關聯has_many/belongs_to,我的評論嵌套在我的活動路線中。這裏是到目前爲止我的代碼 -
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
end
Event.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 %>
其中是註釋/表單的代碼? – jithya
現在在上面添加。 –
我不會再幫你了。上次我花了很多時間在你身上,你說它對你有用,但是0贊成或者標記爲正確! – Fallenhero