首页 > 解决方案 > 从不同的 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

标签: ruby-on-rails

解决方案


使用来自 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 %>

并确保在控制器中使用.includesor.eager_load来避免 N+1 查询:

def show
  @list = List.includes(comments: :user).find(params[:id])
  @current_user = current_user.id
end

推荐阅读