【发布时间】:2016-06-14 04:32:20
【问题描述】:
我正在构建一个具有一些多态关系的 Rails 应用程序,它可以工作,但是我在实现销毁操作时遇到了麻烦。 Comment 表是多态表,Subject has_many :comments 和 profile has_many :comments。我目前正在努力从主题显示页面中删除 cmets(基本上是一个论坛)。我创建了一个 edit_comment_path 并且可以通过 cmets 控制器成功编辑和更新 cmets,但是当我尝试删除时,@comment = Comment.find(params[:id]) 它一直在寻找 Subject.id 而不是 Comment.id?删除的链接似乎是正确的,所以我有点困惑。请看下面的代码。任何建议或改进也将不胜感激!
views/cmets/_comment.html.erb
<% commentable.comments.each do |comment| %>
<div>
<hr>
<% if commentable == @subject %>
<p><%= comment.body %> | Posted by <%= comment.user.email %>, <%= time_ago_in_words(comment.created_at) + ' ago' %></p>
<% if comment.user == current_user %>
<%= link_to "Edit", edit_comment_path(comment, subject: 'subject') %>
<%= link_to "Delete", comment_path, method: :delete %>
<% end %>
<% else %>
<p><<%= comment.title %></p>
<p><%= comment.body %> </p>
<% end %>
</div>
<% end %>
cmets_controller.rb
class CommentsController < ApplicationController
def show
@comment = Comment.find(params[:id])
end
def create
@comment = @commentable.comments.new(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to @commentable, notice: "Successfully Posted!"
end
end
def edit
@comment = Comment.find(params[:id])
end
def update
@comment = Comment.find(params[:id])
if @comment.update(comment_params)
redirect_to @comment.commentable, notice: "Comment was updated."
end
end
def destroy
@comment = Comment.find(params[:id])
end
private
def comment_params
params.require(:comment).permit(:title, :body)
end
end
views/subjects/show.html.erb
<h1><%= @subject.title %></h1>
<p>Created by: <%= @subject.user.email %>, <%= time_ago_in_words(@subject.created_at) + ' ago' %></p>
<%= render partial: 'comments/comment', locals: {commentable: @subject} %>
<%= render partial: 'comments/form', locals: {commentable: @subject} %>
config/routes.rb
Rails.application.routes.draw do
resources :locations, only: [:show, :destroy, :edit, :update]
resources :comments, only: [:show, :edit, :update, :destroy]
resources :subjects, only: [:index, :show] do
resources :comments, module: :subjects
end
resources :profiles do
resources :subjects, module: :profiles
resources :locations, module: :profiles
resources :comments, module: :profiles
end
resource :session, only: [:new, :create, :destroy]
resources :users, only: [:new, :create, :show]
root "home#index"
end
任何反馈将不胜感激
【问题讨论】:
标签: ruby-on-rails ruby activerecord polymorphic-associations ruby-on-rails-5