如何显示用户名和相关帖子?

how to show user name with associated posts?

我正在构建一个 rails 应用程序。我想要一个页面上的所有 post。我可以显示 post 的标题和 body 但我不能显示用户名(post 所属的人 - post 的所有者)。

Post-Model

class Post < ApplicationRecord
    belongs_to :user
end

User-Model

class User < ApplicationRecord
    has_many :posts
end

Posts-Controller

class PostsController < ApplicationController
    def index
        @posts = Post.all
    end   
end

Posts-View index.html.erb

<h1> All article </h1>
<% @posts.each do |post| %>
    <ul>
    <div class="row">
      <div class="col-md-offset-3 col-md-5">
         <h5><b><%= post.title %></b> by <%=  %></h5>
         <p><%= post.body %></p>
      </div>
    </div>
    </ul>
<% end %>

架构看起来像

 create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.string "password_digest"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

post编辑post

的用户的显示名称

尝试 post.user 获取 user 对象。然后你可以打印 user 对象的任何属性。

<p><%= post.user.name %></p>

并使用includes方法避免N+1查询问题。

def index
  @posts = Post.includes(:user)
end  

参考: https://guides.rubyonrails.org/active_record_querying.html

因为你和Post中的User有关系belongs_to :user,所以,你可以简单地使用post.user.name来得到[=的名字15=]喜欢。

<h1> All article </h1>
<% @posts.each do |post| %>
    <ul>
    <div class="row">
      <div class="col-md-offset-3 col-md-5">
         <h5><b><%= post.title %></b> by <%=  post.user.name %></h5>
         <p><%= post.body %></p>
      </div>
    </div>
    </ul>
<% end %>

奖金

如果您想在单个查询中预先加载用户,您可能想要使用。 Post.includes(:user).all,如果你总是使用用户就更好了,可以节省你额外的查询。请注意,它也有一些缺点。

它很容易访问。尝试 post.user.name,您将获得 name 个关联的 user

在此处阅读可用于 belongs_to 关联的所有标准方法 https://guides.rubyonrails.org/association_basics.html#methods-added-by-belongs-to