1

私が最近尋ねた別の質問では、私は本当に良い答えを得て、コードは機能しました...しかし、なぜそれが機能するのか正確にはわかりません...今、私は同様の問題を抱えていますが、それを解決する方法がわかりません。 。?

私が持っているもの:

モデル

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

Thijs

4

2 に答える 2

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を作成しますか?クラス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 %>
于 2011-04-05T12:05:33.777 に答える
1

の反対の結果が必要なようですcan_vote_on?。つまり、ユーザーが回答に投票できない(can_vote_on?falseを返す)場合は、すでに投票している(voted_answer?この場合はtrueを返す必要があります)ことを意味します。その逆も同様です。

これを解決する1つの方法は、次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の原則のため、最初の解決策を好みます。

アップデート

私は否定について間違っていました。この場合、すべてではなく、特定の答えを扱っています。

モデルでは、次のものが必要になります。

def voted_answer? (answer)
    answer.votes.where('votes.user_id = ?', id).exists?
end
于 2011-04-05T11:33:09.747 に答える