【问题标题】:Getting unique values from loop in rails从 Rails 中的循环获取唯一值
【发布时间】:2015-03-16 03:15:52
【问题描述】:

我知道了,所以我有一个临床医生正在与之交谈的独特患者的列表。我可以调出有关患者的详细信息,但无法调出与相关评论有关的任何内容。

app\views\cmets\index.html.erb

    <% @comments.map(&:patient).uniq.each_with_index do |comment, index| %>
      <div class="profile-post color-one">
          <span class="profile-post-numb"><%= index+1 %></span>
          <div class="profile-post-in">
              <h3 class="heading-xs"><a><%= link_to "#{comment.first_name} #{comment.last_name}", comment_path(comment) %></a></h3>
              <p><%= comment.diagnosis %><i class="pull-right"><%= link_to "Edit", edit_comment_path(comment) %> <%= link_to "Delete", comment_path(comment), method: :delete, data: {confirm: 'Are you sure you want to delete'} %></i></p>
          </div>
      </div>
    <% end %>

link_to 也被破坏了,因为它们应该指向评论页面,但传递的是 patient.id 而不是 comment.id。

cmets_conrtoller.rb

def index
 @comments = current_clinician.comments
end

comment.rb

class Comment < ActiveRecord::Base
 belongs_to :clinician
 belongs_to :patient
end

【问题讨论】:

    标签: ruby-on-rails loops uniq do-loops


    【解决方案1】:

    @comments.map(&amp;:patient) 提供属于 Patient 类的对象,这就是链接传递 patient_id 而不是 comment_id 的原因。

    您应该在这里使用group 而不是map

    类似于@comments.group(:patient).. 的东西;必须更改循环语法才能使用此范围的输出。

    有关group 工作原理的更多详细信息,请参阅http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/group

    【讨论】:

    • 我仍然收到:SQLite3::SQLException:没有这样的列:患者:SELECT "cmets".* FROM "cmets" GROUP BY 患者。我已将视图更改为:codecode 和控制器到:codedef index @cmets = Comment.all endcode 现在直到我让它工作。我想我可以使用“有”来让它只显示当前用户的内容
    • @comments.group(:patient_id)... 。我建议在确定要使用的正确循环结构之前在控制台中使用它。
    • 最好的办法是:''感谢您的帮助!
    • 你好,Prakash - 你的建议在本地效果很好,但是当我推送到 heroku 时给了我一个 GroupingError。 PG::GroupingError: ERROR: column "cmets.id" 必须出现在 GROUP BY 子句中或用于聚合函数中 如果您对此有任何建议,将不胜感激
    猜你喜欢
    • 2012-01-12
    • 2017-04-22
    • 2021-05-28
    • 1970-01-01
    • 2015-01-26
    • 2011-06-13
    • 1970-01-01
    相关资源
    最近更新 更多