Ok, I have a simple question. I am new to RoR and I created a scaffold for an item. I then wanted to add a link that, when pressed, incremented a counter. What I am having trouble with is routing. I modeled this functionality after the destroy/delete link and method. Here is my code:
index.html.erb:
...
<td><%= link_to 'Destroy', post, method: :delete %></td>
<td><%= link_to 'increment', post, method: :increment%></td>
...
post_controller.rb:
def vote
@post = Post.find(params[:id])
@post.counts = @post.counts + 1
@post.save
respond_to do |format|
format.html { redirect_to post_url }
format.json { head :ok }
end
end
When I try and click on the link, I get a routing error:
Routing Error
No route matches [POST] “/posts/25”
is there a step I am missing? Do I have to add some routing stuff to get this working?
Ok, hang in here with me, there’s a few fixes needed:
The
:methodparam in thelink_tofunction is not referring to the controller method, it is referring to the HTTP method. So acceptable values would be ‘:post’, ‘:delete’ etc.More info: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
In this case we probably want to set
:methodto:postfor the increment link, which we will need to match with the route we will create now.To access the vote action you have created, we need to add it to the routes file. You probably have something like this:
We need to add an action (vote), that will apply to a member of the posts resource, so we change that to this:
Now that we have the correct route, we can use the route helper method in the
link_tohelper (to see a full list of routes runrake routesat the command line). So in yourlink_toreplacepostwithvote_post_path(post). If we include our earlier change about the:methodwe get:Hope this helps to fill in some blanks for you!