[英]Simple_form path issue
Here is what I have in my view: 这是我的看法:
<%= 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 %>
My ArtistsController: 我的ArtistsController:
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: routes.rb中:
resources :artists do
member do
put "like", to: "artists#upvote"
end
end
I am getting the following error: 我收到以下错误:
No route matches {:action=>"upvote", :controller=>"artists"}
What could be causing this? 是什么原因造成的? How do I get this to work so that the user can select an artist from a collection and vote for that artist?
我如何使它起作用,以便用户可以从收藏集中选择一个艺术家并投票给该艺术家?
There are several issues in your code: 您的代码中存在几个问题:
First, you defined your route as PUT
and you are forcing simple_form
to produce a POST
form. 首先,您将路由定义为
PUT
,并强制simple_form
生成POST
表单。 Change method: :post
to method: :put
in your view and you should be all set. 在您的视图中将
method: :post
更改为method: :put
,您应该已经准备就绪。
Second, you need to define your route according to your controller and action name: 其次,您需要根据控制器和动作名称定义路线:
resources :artists do
member do
put :upvote
end
end
Third, you defined your route as on: :member
. 第三,您将路线定义为
on: :member
。 That means that it needs an artist_id
to generate. 这意味着它需要
artist_id
才能生成。 In your setup, you need to define the route on: :collection
. 在您的设置中,您需要
on: :collection
定义路由。 I'd also better use the route path method instead of url_for
, it's way easier to spot this errors. 我也最好使用route path方法而不是
url_for
,它更容易发现此错误。
resources :artists do
collection do
put :upvote
end
end
And change the url_for
part for update_artists_path
(if that's the correct route from rake routes
). 并将
url_for
部分更改为update_artists_path
(如果这是来自rake routes
的正确rake routes
)。
Another issue not related to your question: :choose_an_artist
is not an attribute defined in Artist
model. 与您的问题无关的另一个问题
:choose_an_artist
不是在Artist
模型中定义的属性。 This will cause another error when rendering the form. 呈现表单时,这将导致另一个错误。
I'd either rename that per the actual attribute name you are selecting, :id
and change the controller accordingly (my choice), or change the form helper from f.input
to a non-model related select_tag
and keep the names as they are. 我可以根据您选择的实际属性名称重命名该名称
:id
并相应地更改控制器(我的选择),或者将表单帮助程序从f.input
更改为与模型无关的select_tag
并保持名称不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.