【问题标题】:Join works in the rails console, but not the view加入在 rails 控制台中有效,但在视图中无效
【发布时间】:2017-07-20 20:33:03
【问题描述】:

我在 Rails 5 中工作。我有两个具有 HABTM 关系的表:publications 和 authors。它们通过连接表 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

作者.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 %>

如何打印与每个出版物相关的作者姓名,而不是打印&lt;Author:xxxxxxxxxxxxxxxx&gt;#

【问题讨论】:

    标签: mysql ruby-on-rails ruby ruby-on-rails-5


    【解决方案1】:

    类似

    <p><%= publication.authors.pluck(:name).join(" ") %></p> 
    

    更改name

    最简单的方法是

    <p><%= publication.authors.map(&:name).join(" ") %></p> 
    

    但第一个更有效:它只返回数据库中的名称,后者返回作者表的所有字段,然后遍历它们以仅具有名称。

    【讨论】:

    • 我的荣幸小姐^_^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多