3

现在,我正在在 Ruby on Rails 上构建一个社交媒体应用程序,我已经实现了一个 5 点投票系统。您可以在哪里对 1-5 发布在网站上的新闻进行投票,我想知道的是,处理投票系统更新的最佳方法是什么。

例如。如果用户已经在一篇文章中投票,我想带回他在文章中给出的分数并软锁定投票(因为我只允许每个用户投 1 票,并且我允许随时更改您的投票),但是如果他还没有,我会以 0 的投票提出这篇文章。

我知道实现这一点的方法,我可以在视图中进行,并检查当前用户是否已经对这篇文章进行了投票,我会将他们发送到 EDIT 视图,否则发送到 SHOW 视图。(我认为)

无论如何,这样做的“正确”方法是什么?

编辑:我忘了说投票组合框是我渲染的一部分。我想只是以某种方式更新部分吗?

编辑2:

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
4

1 回答 1

1

在用户模型中创建一个方法,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 %>

或者您可以在控制器中处理整个事情,并为表单版本和普通版本呈现单独的模板。最佳方法取决于您的具体情况。

编辑2

正如您所发现的,current_user在模型中不起作用。这是有道理的,因为可以从没有会话概念的迁移、库等中调用。

无论如何都不需要访问当前用户,因为您的实例方法(根据定义)在实例上被调用。只需self在模型中引用,并从视图上调用方法current_user,它是User的一个实例:

(在模型中)

  def can_vote_on?(article)
    Article.voted_by(self).include?(article)
  end

(在视图中)

<% if current_user.can_vote_on?(@article) %>

@user或者,current_user如果控制器分配它,您可以替换它。

最后一件事,我认为您的命名范围应该使用user.id,如下所示:

named_scope :voted_by, lambda {|user| {:joins => :votes, :conditions => ["votes.user_id = ?",  user.id]}  }
于 2010-09-03T23:35:11.713 回答