0

我正在使用 Rails 3 和 Devise 2.0

在 Posts 资源的索引视图中,我想显示一个投票按钮,除非 current_user 已经投票。

我只是将@posts = Post.all 传递到索引视图中。检查每个帖子以查看 current_user 是否已经投票并相应地呈现视图的最佳方法是什么?

我目前正在尝试通过voted?在我的 Post 模型中使用一个方法来做到这一点,但是 current_user 方法在那里不可用。

我看到的另一个解决方案是if letter.votes.find_by_user_id(current_user.id)在索引视图中,但我不确定这是否属于视图逻辑。

4

2 回答 2

3

一个好的解决方案是在您的模型或助手中实现一个方法,Post如下所示(假设 post has_many votes):

def voted?(user)
  !votes.find_by_user_id(user.id).empty?
end

然后,在你看来,你可以把if post.voted?(current_user)

你是对的,逻辑属于模型,模型不知道(也不应该)模型之外的任何东西,比如当前用户。您必须将其作为参数传递

于 2012-06-17T02:43:21.947 回答
1

你有一个Post,一个Vote和一个User模型

并且您想知道帖子何时获得特定用户的投票

一种方法可能是贾斯汀的方法,但这会产生过多的数据库查询而不是需要

更好的解决方案是使用这样的has_many :through关联:

class Post
  has_many :votes
  has_many :voted_users, through: :votes, source: :user
end

现在你可以打电话@posts = Post.includes(:voted_users)

这将急切加载对每个帖子投票的所有用户

你可以说

if post.voted_users.include? current_user
  #do stuff
end
于 2012-06-17T07:49:23.883 回答