Rails、link_to 方法::在实例化子元素(注释)后删除中断

Rails, link_to method: :delete breaks after child element (comment) instantiated

我在视频展示页面(属于 post)。 link_to 删除效果很好,直到我在该视频节目页面上创建评论。我进行了一系列水豚测试,验证 link_to 删除视频是否正常工作,直到我对该视频发表评论,此时 rails returns...

Failure/Error: <%= link_to "Delete Video", post_video_path(@video), method: :delete %>

ActionView::Template::Error:
   No route matches

不确定这里发生了什么或如何解决它。我插了一个撬子,前两个命中它的测试我检查了路径...

post_video_path(@video)

返回有效路径,例如

[1] pry(#<#<Class:0x007f891941dee0>>)> post_video_path(@video)
=> "/posts/1/videos/1"

spec实例化注释时,路径如下...

[1] pry(#<#<Class:0x007f891c2fd0a8>>)> post_video_path(@video)
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"videos", :post_id=>#<Video id: 1, user_id: 1, post_id: 1, title: "18title", url: "https://www.youtube.com/watch?v=tYm_182oCVdSM", embed_id: "https://www.youtube.com/watch?v=tYm_182oCVdSM.spli...", tags: nil, created_at: "2016-10-16 22:12:30", updated_at: "2016-10-16 22:12:30">, :video_id=>"1"} missing required keys: [:id]

videos_controller.rb

def show
  @video = Video.find(params[:id])
  @user = @video.user
  @post = @video.post
  @comment = Comment.new
  @comments = @video.comments
end

videos/show.html.erb

<%= @video.title %>
<%= content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{@video.embed_id}") %>
<% binding.pry %>
<%= link_to "Delete Video", post_video_path(@video), method: :delete %>
<%= link_to('Back', user_post_path(@user, @post)) %>

<h3>Comments</h3>

<%= form_for [@video, @comment] do |f| %>
  <%= f.label(:body, "Comment") %>
  <%= f.text_area(:body) %>
  <%= f.submit("Submit Comment") %>
<% end %>

<% @comments.each do |comment| %>
  <%= comment.body %>
  <%= comment.user %>
<% end %>

routes.rb

Rails.application.routes.draw do
  devise_for :users

  resources :users, only: [] do
    collection do
      get '/show_profile', to: 'users#show_profile', as: 'my_profile'
      get '/show_log', to: 'users#show_log', as: 'my_log'
    end
    resources :posts, only: [:new, :create, :show]
  end

  resources :posts do
    resources :videos
  end

  resources :videos do
    resources :comments
  end

  root 'home#index'
end

models/comment.rb

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :video

  validates :body, presence: true
end

如果您想查看任何特定文件或代码,请告诉我。

谢谢!

一般来说 - 当您使用具有两个模型名称的路径名时,您需要将两个模型传递给它。

例如,在您的情况下,您的路径是 post_video_path(@video) - 这期望您将其传递给 postvideo,例如 post_video_path(@post, @video)

如果您不...那么它会变得混乱,可能以您没有预料到的方式。在这种情况下,我猜测它正在获取视频的 ID,并假设它是 post_id.

您可以通过查看此错误消息来判断它是否存在混淆:

ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"videos", :post_id=>#<Video id: 1, user_id: 1, post_id: 1, title: "18title",

特别是具有以下内容的部分::post_id=>#<Video id: 1, ... -> 它将视频放在 post_id 中。很可能它之前只有 "worked" 因为你有一个 post 和一个视频......因此当它使用视频 中的 1 作为 post-id...视频已分配给 post(其 id 也为 1)...但是一旦删除该视频,它就不再存在。这是一个完全的猜测 - 只要你知道错误是从哪里来的,这是否是 Rails 混淆的方式并不重要。