我有两种模式:
一本书属于一个主题,一个主题有很多书籍,我有一个主题索引页面,显示所有主题名称。
index.html.erb
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
<%= form_tag destroy_multiple_subjects_path, method: :delete do %>
<table class="pretty">
<tr>
<th></th>
<th>Username</th>
<th>Subject name</th>
<th>Description</th>
<th>Active</th>
</tr>
<% @subjects.each do |subject| %>
<tr>
<td><%= check_box_tag "subject_ids[]", subject.id %></td>
<td><%= subject.try(:user).try(:username)%></td>
<td data-toggle="tooltip" data-placement="right" title="<%=subject.books%>"><%= subject.name %></td>
<td><%= subject.description %></td>
<td><%= subject.active %></td>
<td><%= link_to 'Show', subject_path(subject) %></td>
<td><%= link_to 'Edit', edit_subject_path(subject) %></td>
</tr>
<% end %>
</table>
<%= submit_tag "Delete selected" %>
<%end%>
现在,当我将鼠标悬停在主题名称(工具提示)上时,我需要显示属于主题的所有书籍。我尝试这样做并获得了有效的记录集(<Book:ActiveRecords_Associations_CollectionProxy:0x007fedfgs>
)但我不知道如何在将鼠标悬停在主题名称上时迭代并显示工具提示中所有书籍的名称。如果我需要提供更多信息,请与我们联系。
答案 0 :(得分:1)
试试这个:
<%= subject.books.map(&:name).join(", ") %> # or whatever attribute to display name of the book
答案 1 :(得分:1)
我建议改用pluck
。
<%= subject.books.pluck(:name).join(', ') %>
也可以设置一些合理的limit
。也许是5?
答案 2 :(得分:0)
执行subject.books
会为您提供ActiveRecord::Associations::CollectionProxy
的对象。您只需要拥有所有书籍的名称,您可以通过写作来完成:
<%= subject.books.map(&:name).join(', ') %>