在我最近问的另一个问题中我得到了一个非常好的答案并且代码有效...但我不确切知道它为什么有效......现在我有类似的问题,但不知道如何解决它...
我有什么:
模型
users
questions (with answer_id)
answers
votes (with answer_id and user_id)
用户模型:
has_many :questions
has_many :votes
def can_vote_on? (question)
!question.answers.joins(:votes).where('votes.user_id = ?', id).exists?
end
def voted_answer? (question)
(what to do here...?)
end
问题模型:
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
在我的问题视图中,当current_used对该特定答案进行投票时,我希望将文本设为粗体。那我该怎么做呢:
<% for answer in @question.answers %>
<% if current_user.voted_answer? (@question) %>
<td>
<strong><%= answer.text %></strong>
</td>
<% else %>
<td>
<%= answer.text %>
</td>
<% end %>
<% end %>
泰斯
答案 0 :(得分:3)
你可以这样做
<% for answer in @question.answers %>
<% if answer.votes.index{|vote| vote.user_id == current_user.id} %>
<td>
<strong><%= answer.text %></strong>
</td>
<% else %>
<td>
<%= answer.text %>
</td>
<% end %>
<% end %>
<强>更新强>
更多逻辑变体创建voted_by_user?在课堂上的功能答案
class Answer
def voted_by_user?(user)
voits.where('votes.user_id = ?', user.id).exists?
end
end
<% @question.answers.each do |answer| %>
<td>
<% if answer.voted_by_user?(current_user) %>
<strong><%= answer.text %></strong>
<% else %>
<%= answer.text %>
<% end %>
</td>
<% end %>
答案 1 :(得分:1)
听起来你只想要can_vote_on?
的相反结果,即如果用户不能对答案投票(can_vote_on?
返回false),那么这意味着他们已经投票({{1}在这种情况下应该返回true),反之亦然。
解决此问题的一种方法是让voted_answer?
返回voted_answer?
的否定:
can_vote_on
当然,你可以使用你在def voted_answer? (question)
!can_vote_on? question
end
中使用的查询而没有否定:
can_vote_on?
但由于DRY原则,我更倾向于第一种解决方案。
<强>更新强>
我对否定感到错误。在这种情况下,您需要处理特定答案,而不是所有答案。
在您的模型中,您需要以下内容:
def voted_answer? (question)
question.answers.joins(:votes).where('votes.user_id = ?', id).exists?
end