Reputation: 475
I am new to ruby on rails.
I am using match ":controller(/:action(/:id))", :via => [:GET, :PUT] as routing system.
I am using acts_as_votable gem to setup voting system for posts.
Currently I am in posts#show page. I have two links one is upvote and the other is downvote.
After I click upvote, I want to hit the posts#upvote action and then redirect to posts#show(same page) page again.
For that i need to pass the parameter of :id(post) in upvote action.
If I use
@post = Post.find(params[:id])
in posts#vote , It throws an error, because we are not passing the :id to params hash.
How to pass the :id(post) to params hash when I click the upvote button inorder to get ridoff the error I am getting.
here is the posts#upvote action code.
def upvote
@post = Post.find(params[:id])
@post.upvote_from User.find(session[:user_id])
redirect_to(:controller => "posts", :action => "show", :id => @post.id)
end
Here is the link tag in posts#show page.
<%= link_to({:controller => "posts", :action => "upvote"}) do %>
<span>Like</span>
<span>(<%= @post.get_upvotes.size %>)</span>
<% end %>
Please help me. Thanks in advance
Upvotes: 0
Views: 2857
Reputation: 9747
Try by hitting following localhost URL from your machine:
localhost:3000/posts/upvote/1 # where 1 is your :id
I would recommend you to go through Ruby on Rais Guides
Upvotes: 0
Reputation: 2463
You're already doing it correctly in the controller, you just need to include the :id in the link_to url options:
<%= link_to(:controller => "posts", :action => "up vote", :id => @post) do %>
<span>Like</span>
<span>(<%= @post.get_upvotes.size %>)</span>
<% end %>
Note: you don't need to call id
on the post, rails will automatically figure this out for you.
A better solution, would be to use resource routes for you Post object. then add upvote/downvote actions:
# in config/routes.rb
resources :posts do
member do
match "upvote", :as => :upvote, :via => [:get, :put]
end
end
Rails will automatically create url helpers that you can use in your views
# in show html.erb
<%= link_to(upvote_post_url(@post)) do %>
<span>Like</span>
<span>(<%= @post.get_upvotes.size %>)</span>
<% end %>
the advantage to this is simpler code, and the ability change your routes with having to update template code.
Rails has already done all the heavy lifting of how to make and link to urls, to be faster at plumbing rails views and controllers together, you should definitely read the official guides http://guides.rubyonrails.org/routing.html, then may look daunting at first, but they will quickly become second knowledge.
Upvotes: 3
Reputation: 882
Something like this
EDITED:
<%= link_to "Upvote", "#{Rails.root}/posts/upvote/#{@post.id}" %>
Passing in the @post.id will pass in that object's id in the params hash (as params[:id]).
Upvotes: 2