Rails 中链接点击次数计数问题
我有一个数据库,其中包含许多记录,每条记录都有一个关联的 URL。目前,我已经进行了一些设置,以便当人们单击特定记录的链接时,他们会被重定向到适当的 URL。目前的代码是:
<%= link_to image_tag( alldata.picture.to_s + ".gif"), alldata.URL_link %>
这很好地完成了它的工作。我现在想修改它,以便当单击链接时,一个名为 :click_count
的参数对于所有记录最初设置为 0。
阅读周围,我相信您可以使用以下形式来完成此操作:
<%= link_to image_tag( alldata.picture.to_s + ".gif"), alldata.URL_link, {:controller => params[:controller], :action => "clickcountplusone", :product_name => alldata.product_name} %>
在控制器中使用以下内容:
def clickcountplusone
clickeditem = Entiredatabase.find(params[:product_name])
clickeditem.update_attribute(:click_count => clickeditem.click_count + 1)
end
虽然这不会产生错误,但它也不会增加计数...任何人都可以阐明问题?
I have a database with a number of records in it, each with an associated URL. Currently I have things set up so that when people click on a link for a particular record they get redirected to the appropriate URL. The code is currently:
<%= link_to image_tag( alldata.picture.to_s + ".gif"), alldata.URL_link %>
This does its job fine. I would like to now modify this so when the link is clicked on, a parameter called :click_count
which is orignally set to 0 for all records.
Reading around, I believe you can do this using something of the following form:
<%= link_to image_tag( alldata.picture.to_s + ".gif"), alldata.URL_link, {:controller => params[:controller], :action => "clickcountplusone", :product_name => alldata.product_name} %>
With the following in the controller:
def clickcountplusone
clickeditem = Entiredatabase.find(params[:product_name])
clickeditem.update_attribute(:click_count => clickeditem.click_count + 1)
end
Although this does not produce an error, it also doesn't increase the count number... Could anyone shed any light on the issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上不需要为此采取单独的操作。相反,只需使用默认的
show
操作,并在调用操作时递增计数器,如下所示:但是,每当查看该页面时,这都会递增计数器 - 因此,如果您只想跟踪以下视图跟随特定链接,您可以执行以下操作:
然后在 link_to 帮助程序中添加一个额外的参数:
希望这会有所帮助。
You shouldn't really need a separate action for this. Instead, simply use the default
show
action, and increment the counter whenever the action is called, like this:This will however increment the counter whenever that page is viewed - so if you want to only track views that followed a particular link, you could do something like:
And then in your link_to helper, add an extra param:
Hope this helps.
您对
update_attribute
的语法是错误的:应该是:
小心,
update_attribute
接收(name, value)
和update_attributes
接收一个哈希
。更多信息此处另请查看增量计数器
Your sintax on
update_attribute
is wrong:should be:
Be carefull,
update_attribute
receives a(name, value)
andupdate_attributes
receives ahash
. More information hereAlso take a look to increment counter