Simple_form 路径问题

Simple_form path issue

以下是我的看法:

<%= simple_form_for :artist, :url => url_for(:action => 'upvote', :controller => 'artists'),
    :method => 'post' do |f| %>
  <%= f.input :choose_an_artist, :selected => "first artist", collection: [["first artist", 1], ["second artist", 2], ["third artist", 3], ["fourth artist", 4]] %>

  <%= f.submit "Vote" %>
<% end %>

我的艺术家控制器:

def upvote
  @artist = Artist.find(params[:choose_an_artist])
  @artist.liked_by current_user

  respond_to do |format|
    format.html {redirect_to :back }
  end
end

routes.rb:

resources :artists do
  member do
    put "like", to: "artists#upvote"
  end
end

我收到以下错误:

No route matches {:action=>"upvote", :controller=>"artists"}

这可能是什么原因造成的?我如何让它工作,以便用户可以 select 来自 collection 的艺术家并投票给该艺术家?

您的代码中存在几个问题:

首先,您将路线定义为 PUT 并且您正在强制执行 simple_form 生成 POST 表格。改变 method: :postmethod: :put 在你看来,你应该已经准备好了。

其次,您需要根据您的控制器和动作名称定义您的路线:

resources :artists do
   member do
     put :upvote
   end
 end

第三,您将路线定义为on: :member。这意味着它需要一个 artist_id 来生成。在您的设置中,您需要定义路线 on: :collection。我也最好使用路由路径方法而不是 url_for,它更容易发现这个错误。

resources :artists do
   collection do
     put :upvote
   end
 end

并更改 update_artists_pathurl_for 部分(如果这是来自 rake routes 的正确路线)。

另一个与您的问题无关的问题::choose_an_artist 不是 Artist 模型中定义的属性。这将在呈现表单时导致另一个错误。

我会根据您选择的实际属性名称重命名 :id 并相应地更改控制器(我的选择),或者将表单助手从 f.input 更改为非模型相关 select_tag 并保持名称不变。