ruby-on-rails - 从不同的 Active Record 模型/表中检索一条数据
问题描述
任何建议将不胜感激。
是否可以在 list#show/show.html.erb 视图中检索用户使用的电子邮件地址、发表评论?没有在我的评论模型中添加另一列“电子邮件”?
我能做的最好的就是检索 user_id,这没什么帮助。
<% @list.comments.each do |comment| %>
<p><%= comment.body%></p>
<p><%= comment.user_id %>
<% end %>
评论.rb
class Comment < ApplicationRecord
belongs_to :list, optional: true
belongs_to :user
评论表
create_table "comments", force: :cascade do |t|
t.text "body"
t.bigint "list_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "user_id"
t.index ["list_id"], name: "index_comments_on_list_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
列表控制器#show
def show
@list = List.find(params[:id])
@current_user = current_user.id
end
解决方案
使用来自 ActiveSupport 的Module#delegate :
class Comment < ApplicationRecord
belongs_to :list, optional: true
belongs_to :user
delegate :email, to: :user
end
<% @list.comments.each do |comment| %>
<p><%= comment.body%></p>
<p><%= comment.user_id %>
<p><%= comment.email %>
<% end %>
并确保在控制器中使用.includes
or.eager_load
来避免 N+1 查询:
def show
@list = List.includes(comments: :user).find(params[:id])
@current_user = current_user.id
end
推荐阅读
- arkit - ARKit 4 | 导出点云
- mysql - 无法使用 PhpStorm 连接到外部 MySQL 服务器
- reactjs - Internet Explorer 11 上的 SCRIPT5017 错误,使用 webpack 4、babel 7 并做出反应
- javascript - 有没有办法优化这个 Promise 循环,这样我就不会出现 FATAL JavaScript heap out of memory 错误了?
- python - 试图从另一个函数中捕获异常
- java - 如何更改单击的按钮的颜色,但使其只能同时更改一个按钮的颜色?
- django - 以 HTML 格式发送电子邮件不显示上下文
- graphics - 如何计算图形和方程中带有 x 的值的值?
- python - 如何使用 PyGame 制作“退出”按钮单击事件以关闭程序
- javascript - (猫鼬)如何在帖子和评论模型之间进行双向引用