在另一個問題,我最近問我得到了一個非常好的答案和代碼工作...但我不知道它到底爲什麼它的工作...現在我有類似的問題,但不知道如何解決它...?查詢在rails3
我有:
模型
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 %>
泰斯
謝謝,但它不工作...現在我得到人的結果大膽的,因爲如果任何votes.user_id的存在查詢檢查......我只wnat的CURRENT_USER。 id投票答案... – Thijs 2011-04-05 11:43:52
@Thijs - 疑惑,我不確定在那個電話裏id是從哪裏來的。你有沒有嘗試用current_user.id代替我在第二個例子中顯示的id?我想'can_vote_on?'也在使用當前用戶的ID。 – McStretch 2011-04-05 12:03:29
我試過了,但是我總是得到未定義的方法錯誤:def voted_on? (問題) question.answers.joins(:votes).where('votes.user_id =?',current_user.id) end – Thijs 2011-04-05 12:08:58