1

我从 php 迁移到 rails3,我仍然认为这是一个不错的决定!无论如何,我有一些模型:

users
questions
answers
question_id
votes
user_id
answer_id

用户型号:

has_many :questions
has_many :votes

问题模型:

belongs_to :user
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? }, :allow_destroy => true

答案模型:

belongs_to :question
has_many :users, :through => :votes, :dependent => :destroy
has_many :votes

投票模型:

belongs_to :answer
belongs_to :user

现在我的问题是,一旦用户对答案进行了投票,就应该关闭对该用户和该特定问题的投票...

我在我的项目的其余部分中使用设计和 cancan 作为用户和授权......

在我看来,它应该看起来像:

<% unless current_user.question_answered.include? question %>

然后在我渲染投票按钮的地方执行脚本......

在我的投票模型中,我有一个 answer_id 和一个 user_id,我知道 current_user.id 和当前 question.id 所以如果 vote.user_id 有当前 question.id 中的 vote.answer_id ,那么它不应该呈现我的按钮制作脚本... aarghh 但是如何使它工作...?

首先十分感谢!最好的问候, Thijs

4

2 回答 2

2

我会亲自走出设计并编写自己的方法。我认为它更干净,更容易理解。您还将使用此方法保证您只对数据库执行一次快速查询。通过询问current_user.questions_answered您正在查询数据库以查找用户已回答的所有问题,这可能比检查用户是否对当前问题进行了投票更大的结果集:

class User
  def can_vote_on? question
    !question.answers.joins(:votes).where('votes.user_id = ?', id).exists?
  end
end

然后,您可以将视图调整为:

<% if current_user.can_vote_on?(question) %>
于 2011-04-02T16:31:40.200 回答
1

有能力写这样的东西

can :vote, Answer, :votes => { :users => user }

在你看来,做类似的事情

<% if can? :vote, Answer %>

(我现在不能真正测试它,所以让我知道它是否有效)

于 2011-04-02T16:08:53.997 回答