2011-04-05 51 views
1

在另一個問題,我最近問我得到了一個非常好的答案和代碼工作...但我不知道它到底爲什麼它的工作...現在我有類似的問題,但不知道如何解決它...?查詢在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 %> 

泰斯

回答

1

這聽起來像你只是想can_vote_on?相反的結果,即如果用戶不能在答案投票(can_vote_on?返回false),那麼就意味着他們已經投了票(voted_answer?應該在這種情況下返回true),反之亦然。要解決這個

一種方法是有voted_answer?返回can_vote_on的否定:

def voted_answer? (question) 
    !can_vote_on? question 
end 

或者當然你可以使用你can_vote_on?使用,而否定查詢:

def voted_answer? (question) 
    question.answers.joins(:votes).where('votes.user_id = ?', id).exists? 
end 

但由於DRY原則,我更喜歡第一種解決方案。

UPDATE

我錯了否定。在這種情況下,你正在處理一個特定的答案,而不是所有的答案。

在你的模型,你會希望以下內容:

def voted_answer? (answer) 
    answer.votes.where('votes.user_id = ?', id).exists? 
end 
+0

謝謝,但它不工作...現在我得到人的結果大膽的,因爲如果任何votes.user_id的存在查詢檢查......我只wnat的CURRENT_USER。 id投票答案... – Thijs 2011-04-05 11:43:52

+0

@Thijs - 疑惑,我不確定在那個電話裏id是從哪裏來的。你有沒有嘗試用current_user.id代替我在第二個例子中顯示的id?我想'can_vote_on?'也在使用當前用戶的ID。 – McStretch 2011-04-05 12:03:29

+0

我試過了,但是我總是得到未定義的方法錯誤:def voted_on? (問題) question.answers.joins(:votes).where('votes.user_id =?',current_user.id) end – Thijs 2011-04-05 12:08:58

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 %> 

UPDATE

更合乎邏輯的變種創建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 %> 
+0

哇它的工作聲望需要票...但你能解釋它爲什麼工作? – Thijs 2011-04-05 12:14:20

+0

好吧,我明白了!您將vote.id與vote.id與answer.id中的vote.user_id – Thijs 2011-04-05 12:21:15

+0

答案進行比較,結果中包含voits。 voits參考用戶。如果current_user.id == voit.user_id - 這意味着此用戶對此答案發表意見 – Sector 2011-04-05 12:27:10