在 Rails 中提交新表单时没有路由匹配 [POST]

No route matches [POST] when submitting new form in Rails

我在提交新表单时收到 "No route matches [POST]"。

### /routes.rb ###

resources :artists, controller: 'artists/artists', only: [:show] do
  member do
    resources :videos, controller: 'artists/videos', only: [:index, :new, :create, :edit, :update]
  end
end

### /artists/videos/videos_controller.rb ###

class Artists::VideosController < ApplicationController
  before_action :set_artist

  def new
    @video = ArtistVideo.new
  end

  def create
    @video = @artist.create_artist_video(video_params)
    if @video.save
      redirect_to current_artist
    else
      render 'new'
    end
  end

   private
     def set_artist
       @artist = current_artist
     end
end

### /artists/videos/new.html.erb ###

<%= form_for(@video, url: new_video_path) do |f| %>
    <%= f.label :video_title, "title", class: "label" %>
    <%= f.text_field :video_title, class: "text-field" %>

    <%= f.label :video_description, "decription", class: "label" %>
    <%= f.text_field :video_description, class: "text-field" %>

    <%= f.label :youtube_video_url, "youtube url", class: "label" %>
    <%= f.text_field :youtube_video_url, class: "text-field" %>

    <%= f.submit "add video", class: "submit-button" %>
<% end %>

### rake routes ###

videos_path         GET      /artists/:id/videos(.:format)          artists/videos#index
                    POST     /artists/:id/videos(.:format)           artists/videos#create
new_video_path      GET      /artists/:id/videos/new(.:format)       artists/videos#new
edit_video_path     GET      /artists/:id/videos/:id/edit(.:format)  artists/videos#edit
video_path          PATCH    /artists/:id/videos/:id(.:format)       artists/videos#update
                    PUT      /artists/:id/videos/:id(.:format)       artists/videos#update

所以不确定我在这里做错了什么。我试过完全去掉 :index 所以 videos_path 使用 post 方法,但我仍然有同样的问题。

我正在使用 has_many 方法将视频链接到艺术家,如果这很重要的话。

不确定是路由错误还是控制器代码错误。任何帮助将不胜感激。

您正在指定一个路径 url: new_video_path 但那是针对 videos#new 而您 想要的 是创建路径,它是一个 post 到 videos_path(@artist)。由于它是嵌套资源,因此路径必须具有可以从 @artist 实例获取的 artist_id。

但是,更简单的方法是这样的:

form_for[@artist, @video] do |f|