0
我有我的多態關聯的問題。在使用此代碼<%= link_to "Edit", edit_blog_comment_path(comment) %>
時,編輯鏈接顯示在我的查看頁面中。我試圖啓用評論的編輯,在這種情況下,該評論屬於博客。但是,鏈接實際上指向.../blogs/7/comments/3/edit
時,它應該是相反的。博客ID是3,評論ID是7.這是所有評論的方式。我堅持找到錯誤的位置。什麼導致他們交換?態關聯路線倒退
我的路線:
blog_comments GET /blogs/:blog_id/comments(.:format) comments#index
POST /blogs/:blog_id/comments(.:format) comments#create
new_blog_comment GET /blogs/:blog_id/comments/new(.:format) comments#new
edit_blog_comment GET /blogs/:blog_id/comments/:id/edit(.:format) comments#edit
blog_comment GET /blogs/:blog_id/comments/:id(.:format) comments#show
PATCH /blogs/:blog_id/comments/:id(.:format) comments#update
PUT /blogs/:blog_id/comments/:id(.:format) comments#update
DELETE /blogs/:blog_id/comments/:id(.:format) comments#destroy
blogs GET /blogs(.:format) blogs#index
POST /blogs(.:format) blogs#create
new_blog GET /blogs/new(.:format) blogs#new
edit_blog GET /blogs/:id/edit(.:format) blogs#edit
blog GET /blogs/:id(.:format) blogs#show
PATCH /blogs/:id(.:format) blogs#update
PUT /blogs/:id(.:format) blogs#update
DELETE /blogs/:id(.:format) blogs#destroy
而且我的意見控制器
class CommentsController < ApplicationController
before_action :load_commentable
before_action :authenticate_user!, except: [:index, :show]
def index
@comments = @commentable.comments
end
def edit
end
private
def load_commentable
resource, id = request.path.split('/')[1,2]
@commentable = resource.singularize.classify.constantize.find(id)
end
def allowed_params
params.require(:comment).permit(:content, :user_id)
end
end
我_comments.html.erb。如果後半部分看起來很醜陋,那是因爲我不能在我的生活中獲得@commentable變量來處理編輯和刪除路徑,所以我只是做了一個條件語句。
<div id="articles-wrapper">
<% @comments.each do |comment| %>
<div class="articles">
<div class="post-title"><%= comment.content.html_safe %></div>
<div class="date">Posted <%= time_ago_in_words(comment.created_at) %> ago by <%= link_to comment.user.username, user_path(comment.user) %>
<% if @commentable = @blog %>
<%= link_to edit_blog_comment_path(comment) do %><i class="fa fa-pencil"></i><% end %>
<%= link_to blog_comment_path(comment), method: :delete, data: { confirm: "Are you sure?" } do %><i class="fa fa-times"></i><% end %>
<% else %>
<%= link_to edit_article_comment_path(comment) do %><i class="fa fa-pencil"></i><% end %>
<%= link_to article_comment_path(comment), method: :delete, data: { confirm: "Are you sure?" } do %><i class="fa fa-times"></i><% end %>
<% end %>
</div>
</div>
<% end %>
</div>
你'edit_blog_comment_path'需要一個'blog_id'和' id'作爲評論('/ blogs /:blog_id/comments /:id/edit')。無論你在哪裏產生斷開的鏈接,都要檢查你傳遞給url助手的兩個id,並確保它們是正確的。我沒有看到代碼中的任何地方,你從參數中抓取博客對象(例如'@blog = Blog.find(params [:blog_id])')。 – mmichael
這不就是load_commentable的作用嗎?我編輯了我的問題以包含routes.rb。 – ddonche
我編輯了您的問題以刪除不相關的代碼。所有'load_commentable'都會填充'@ commentable'變量 - 你仍然需要使用它。請郵寄產生的編輯鏈接('edit_blog_comment_path(評論)'),這是代碼(可能是從你的'index.html.erb'圖,其中您的問題是,你需要同時通過'blog_id'和註釋[ 'id']到'edit_blog_comment_path'幫手。 – mmichael