当我删除我的评论时,我的帖子也被删除了,这里是我的MVC:
观点(在_comments.html.erb中)
<%= div_for(comment) do %>
<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.email %></small></p>
</div>
<div class="btn-group pull-right">
<% if comment.user == current_user -%>
<%= link_to 'Destroy', @comment, method: :delete, data: { confirm: 'Are you sure?' }, class: "btn btn-sm btn-default" %>
<% end %>
</div>
</div>
<% end %>
型号:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
end
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
控制器
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def destroy
@post = Post.find params[:post_id]
@comment = @post.comments.find params[:id]
@comment.destroy
redirect_to post_path(@post)
end
路线
resources :post do
resources :comments
end
当我删除评论时,我甚至会收到闪光通知:
您的帖子已被删除
位于后置控制器......