从其他Active Record模型/表中检索数据

时间:2020-04-24 17:33:01

标签: ruby-on-rails

任何建议将不胜感激。

是否可以在list#show / show.html.erb视图中检索用户发表评论的电子邮件地址?没有在我的评论模型中添加另一列“电子邮件”?

我能做的最好的事情就是检索user_id,这没有帮助。

<% @list.comments.each do |comment| %>
  <p><%= comment.body%></p>
  <p><%= comment.user_id %> 
<% end %>

Comment.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

1 个答案:

答案 0 :(得分:0)

使用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.eager_load以避免N + 1查询:

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