我在Rails 5工作。我有两个HABTM关系表:出版物和作者。它们通过连接表authors_publications连接。
我试图让视图列出与每个出版物相关联的作者的姓名,并且它返回此信息: the view
它的作者数量是正确的,但我希望它能打印实际的名字。当我在我的控制台中尝试此操作时,连接正常工作。这是我的应用中的相关代码:
publication.rb
class Publication < ApplicationRecord
self.table_name = "publications"
has_and_belongs_to_many :authors
scope :sorted, lambda { order("year_published DESC") }
scope :newest_first, lambda { order("created_at DESC") }
#scope :search, lambda {|query| where(["name LIKE ?", "%#{{query}}"])
#}
end
author.rb
class Author < ApplicationRecord
self.table_name = "authors"
has_and_belongs_to_many :publications
end
index.html.erb
<% @publications.each do |publication| %>
<h3><%= publication.name %></h3>
<p><%= publication.citation %></p>
<p><%= publication.authors.join(" ") %></p>
<% end %>
如何打印与每个出版物相关联的作者姓名,而不是打印<Author:xxxxxxxxxxxxxxxx>#
?
答案 0 :(得分:2)
像
这样的东西<p><%= publication.authors.pluck(:name).join(" ") %></p>
更改name
列
最明智的方法是
<p><%= publication.authors.map(&:name).join(" ") %></p>
但第一个更有效:它只返回数据库中的名称,后者返回authors表的所有字段,然后迭代它们以获得名称。