[英]Voting update on Ruby on Rails
现在,我正在Ruby on Rails上构建一个社交媒体应用程序,我已经实现了一个5点投票系统。 你可以在1-5的位置投票给网站上发布的新闻,我想知道的是,处理投票系统更新的最佳方法是什么。
在例子中。 如果用户已经在一篇文章中投票,我想带回他在文章中给出的分数并软锁定投票(因为我只允许每个用户投1票,我允许随时更改您的投票),但是如果他不会在0投票时提出这篇文章。
我知道一种方法可以实现这一点,我可以在视图中执行此操作,并检查当前用户是否已经对此文章进行了投票,我将其发送到EDIT视图,否则将其发送到SHOW视图。 (我认为)
无论如何,这样做的“正确”方法是什么?
编辑:我忘了说投票组合框它是我正在渲染的部分。 我想只是以某种方式更新部分?
EDIT2:
class Article < ActiveRecord::Base
has_many :votes
belongs_to :user
named_scope :voted_by, lambda {|user| {:joins => :votes, :conditions => ["votes.user_id = ?", user]} }
end
class User < ActiveRecord::Base
has_many :articles
has_many :votes, :dependent => :destroy
def can_vote_on?(article)
Article.voted_by(current_user).include?(article) #Article.voted_by(@user).include?(article)
end
end
如果用户可以对文章进行投票,则在User模型中创建一个响应为true
的方法:
class User < ActiveRecord::Base
...
def can_vote_on?(article)
articles_voted_on.include?(article) # left as an exercise for the reader...
end
end
在视图中,如果用户可以编辑,则渲染表单,否则渲染普通视图:
<% if @user.can_vote_on?(@article) %>
<%= render :partial => "vote_form" %>
<% else %>
<%= render :partial => "vote_display" %>
<% end %>
或者您可以在控制器中处理整个事情,并为表单版本和普通版本呈现单独的模板。 最好的方法取决于您的具体情况。
EDIT2
如您所见, current_user
在模型中不起作用。 这是有道理的,因为可以从迁移,库等调用,其中没有会话的概念。
无论如何都不需要访问当前用户,因为您的实例方法(根据定义)在实例上被调用。 只需在模型中引用self
,然后从current_user
视图中调用方法, current_user
是User的一个实例:
(在模型中)
def can_vote_on?(article)
Article.voted_by(self).include?(article)
end
(在视图中)
<% if current_user.can_vote_on?(@article) %>
或者,如果控制器分配了@user
,则可以用@user
替换current_user
。
最后一件事,我认为你的命名范围应该使用user.id
,如下所示:
named_scope :voted_by, lambda {|user| {:joins => :votes, :conditions => ["votes.user_id = ?", user.id]} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.