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

时间:2015-01-10 23:42:08

标签: ruby-on-rails forms ruby-on-rails-4 routing rails-routing

我得到一个"没有路线匹配[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

所以不确定我在这里做错了什么。我尝试过:完全索引,所以videos_path使用post方法,但我仍然遇到同样的问题。

我使用has_many方法将视频与艺术家联系起来,如果这甚至很重要的话。

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

1 个答案:

答案 0 :(得分:4)

您指定的路径为url: new_video_path,但适用于videos#new,而您想要的是创建路径,这是videos_path(@artist)的帖子。由于它是嵌套资源,因此路径必须具有可从@artist实例获取的artist_id。

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

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