在我最近问的另一个问题中,我得到了一个非常好的答案并且代码有效......但我不知道它为什么有效......现在我有一个类似的问题,但不知道如何解决它……?
我有什么:
模型
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
在我的问题 View 中,当 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 %>
泰斯
最佳答案
你可以这样做
<% 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? Answer类中的函数
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 %>
关于ruby - 在 rails3 中查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5550623/