Reputation: 5000
i want to update viewcount value in Posts table when user click the "like" link in post........
model
class Post < ActiveRecord::Base
belongs_to :user
has_many :answers
attr_accessible :acceptedanswerid, :body, :userid, :tag, :title, :viewcount, :vote, :anscount
validates_presence_of :title ,:body ,:tag
scope :unanswered, where(:anscount => 0)
scope :byvote, where(:vote=>maximum("vote"))
end
controller
post_controller.rb
class PostController < ApplicationController
def index
@post=Post.new
@answer=Answer.new
@anscomment=Anscomment.new
@posts=(Post.all).reverse
@posts1=Post.all(:limit => 5 ,:order => "id desc")
@unanswered = Post.unanswered
@byvote=Post.byvote
#fid=params[:fid]
session[:flag]=nil
fid=params[:fid]
session[:flag]=fid
end
#def new
# @post=Post.new
# end
def create
# @post=Post.new(params[:post])
@post=Post.new(params[:post])
respond_to do |format|
if @post.save
#if (session[:flag!=nil])
#session[:flag]=1
#end
format.html { redirect_to :controller=>"post" ,:action=>"index" }
format.json { render json: @post, status: :created, location: @post }
#redirect_to :controller=>"post" ,:action=>"index"
else
#session[:flag]=3
format.html { redirect_to :controller=>"home" ,:action=>"index" }
format.json { render json: @post, status: :created, location: @post }
#redirect_to :controller=>"post" ,:action=>"index"
end
end
end
def show
id=params[:id]
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
def vote
vcount = User.find(params[:id])
vcount.update_attribute(:viewcount, vcount.viewcount + 4)
end
end
view
views/post/show.html.erb
<table align=center width="60%" bordercolor="black" >
<tr>
<td align="center">
<h2>
<%[email protected]%>
</h2>
</td>
</tr>
<tr>
<td align="center" width="60">
<h3><%[email protected]%></h3>
</td>
</tr>
<tr>
<td align="center">
This Post comes under:<%[email protected]%>
</td>
</tr>
<tr >
<td align="right">
<%[email protected] %>
<%if id==nil %>
<%id='15'%>
<%end%>
<%@user=User.find(id)%>
posted by:<%[email protected]%> <p>on <%[email protected]_at%></p>
<%id=nil%>
<h1 align="left"><%[email protected]%></h1>
<!--<%Post.increment_counter(:viewcount,@post.id) %>-->
<%= link_to "like", {:controller => "post", :action => "vote", :id => @post.id } %>
</td>
</tr>
</table>
when i click the "like" the like link i am getting an error like-----Couldn't find Post with id=vote
*application trace: * app/controllers/post_controller.rb:42:in `show'
plz help me finding the error.......
Upvotes: 0
Views: 306
Reputation: 5437
i think it happens because in your routes.rb file /post/:id
is before :controller/:action:/:id
, so u have to create named route for this action.
resources :posts do
get 'vote', on: member
end
and the use path helper vote_post_path(post)
http://guides.rubyonrails.org/routing.html
Upvotes: 1