如何在 table 中获取用户名,其中 user_id 用作外键

How can i get User name in a table where user_id is used as foreign key

我正在使用 Devise gem 进行用户身份验证。用户 ID 作为文章 table 中的外键 如何在视图 Show_article.html.erb 中通过 User_id 获取作者姓名 我可以在 show_article.htmlerb

中访问 user_id

我尝试在文章控制器中创建自定义函数,但无法获得所需的输出

您的文章模型应如下所示:

class Article << ActiveRecord::Base
  belongs_to :user
  #....some more lines
end

您的用户模型应该如下所示:

class User << ActiveRecord::Base
  has_many :articles
  #....some more lines
end

你的show.html.erb应该说:

  #....your rest of code
<%= @article.try(:user).try(:name) %>
  #....your rest of code

如果您的文章没有任何用户,这将跳过用户名。看起来你的文章没有 user_id 或者你没有正确定义你的关系。

可能是您的某些文章没有任何用户。所以 你可以做到

<%= @article&.user&.name %> 显示页面

并在索引页中

<% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= article&.user&.name%></td>
      <td><%= link_to 'Show', article_path(article) %></td>
      <td><%= link_to 'Edit', edit_article_path(article) %></td>
      <td><%= link_to 'Delete', article_path(article),
              method: :delete,
              data: { confirm: 'Are you sure you want to delete this article?' } %></td>
    </tr>
  <% end %>

但请确保您拥有 ruby 2.3.0 或更高版本