Katie H
Katie H

Reputation: 2293

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:

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

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?

Upvotes: 0

Views: 1589

Answers (1)

dgilperez
dgilperez

Reputation: 10796

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. Change method: :post to method: :put in your view and you should be all set.

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. That means that it needs an artist_id to generate. In your setup, you need to define the route on: :collection. I'd also better use the route path method instead of url_for, it's way easier to spot this errors.

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).

Another issue not related to your question: :choose_an_artist is not an attribute defined in Artist model. 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.

Upvotes: 1

Related Questions