我正在构建一个Rails应用程序。我想全部张贴在页面上。我可以显示帖子的标题和正文,但不能显示用户名(帖子所属的用户-帖子的所有者)。
后模型
class Post < ApplicationRecord
belongs_to :user
end
用户模型
class User < ApplicationRecord
has_many :posts
end
职位控制器
class PostsController < ApplicationController
def index
@posts = Post.all
end
end
帖子查看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
显示发布该帖子的用户的名称
由于您User
与Post
as中的关系belongs_to :user
,因此,您只需使用post.user.name
即可获得user
like的名称。
<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
,如果您始终使用该用户会更好,这样可以节省额外的查询。请注意,它也有一些缺点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句