我正在构建一个Rails应用程序。我想全部张贴在页面上。我可以显示帖子的标题和正文,但不能显示用户名(帖子所属的用户-帖子的所有者)。
后期模型
class Post < ApplicationRecord
belongs_to :user
end
用户模型
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
显示发布该帖子的用户的姓名
答案 0 :(得分:0)
尝试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
答案 1 :(得分:0)
由于您与User
中的Post
有一个belongs_to :user
关系,因此,您可以简单地使用post.user.name
来获取{{1} }。
user
如果您希望在单个查询中加载用户,则可能要使用。 <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 %>
(如果您始终使用用户会更好)为您节省了额外的查询。请注意,它也有一些缺点。
答案 2 :(得分:0)
访问非常容易。尝试使用post.user.name
,您将获得name
的关联user
。
在此处阅读有关belongs_to
关联可用的所有标准方法的信息
https://guides.rubyonrails.org/association_basics.html#methods-added-by-belongs-to