ruby - 在 rails3 中查询

标签 ruby ruby-on-rails-3 rails-models

在我最近问的另一个问题中,我得到了一个非常好的答案并且代码有效......但我不知道它为什么有效......现在我有一个类似的问题,但不知道如何解决它……?

我有什么:

模型

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/

相关文章:

ruby - MongoDB:如何存储大数组? (ERR Document too large: This BSON documents is limited to 16777216 bytes)

Rubygems:可以在 gem 分发中使用符号链接(symbolic link)吗?

ruby floats 根据顺序加起来不同的值

javascript - Rails3 使用 text/html 内容类型而不是 text/javascript 呈现 js.erb 模板

mysql - 创建具有特定键长度的索引的启发式方法?

ruby-on-rails - Rspec 测试中 nil 类的未定义方法

ruby - 使用 Nix 在本地构建 GitHub 页面

ruby-on-rails - Rails - 使用 ajax 上传图片

mysql - 将Redis与Rails结合使用会为这种特定类型的查询提供任何性能优势

ruby-on-rails - 函数中的puts语句未执行,函数测试失败,但收到(:function) spec works