【发布时间】:2020-02-28 12:04:25
【问题描述】:
在对话控制器中,我有以下内容:
def users_with_existing_conversations
authorize! :users_with_existing_conversations, Conversation
@users = User.accessible_by(current_ability, :index_conversations)
@users = @users.where(id: Conversation.select(:sender_id))
.or(@users.where(id: Conversation.select(:recipient_id)))
@users = @users.search(params[:query]) if params[:query].present?
@users = sort_and_paginate(@users)
set_meta_tags title: "Existing Conversations", reverse: true
end
在用户模型中,我有这个has_many relaitonship:
has_many :sender_conversations, class_name: 'Conversation', foreign_key: "sender_id", dependent: :destroy
has_many :recipient_conversations, class_name: 'Conversation', foreign_key: "recipient_id", dependent: :destroy
在控制器模型中,我有 belongs_to 关联:
belongs_to :sender, foreign_key: :sender_id, class_name: 'User'
belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'
回到控制器,@users 对象正在被渲染到视图中。我需要会话表中的一个附加列,即last_updated 列。
所以基本上我想从conversation 表中向@users 添加一个键值对
我尝试过类似的东西
@users.each do |user|
user[:latest_conversation] = Conversation.where(sender_id: user.id)
end
导致can't write unknown attribute latest_conversation
我也尝试过类似的测试查询
@testUsers = @users.sender_conversations
导致undefined method sender_conversations
正如您在上面看到的,我的模型中有关联。文档显示了示例,我认为这会起作用
在我看来,我有:
<% @users.each do |user| %>
<tr class="table__row" onclick="window.location.href = '/conversations?user_id=<%= user.id %>'">
<td><%= user.name %></td>
<td><%= user.surname %></td>
<td><%= user.email %></td>
<td><%= user.company_name.present? ? user.company_name : "N/A" %></td>
<td><%= user.role.capitalize %></td>
<td><%= user.created_at.try(:strftime, '%b %d, %Y') %></td>
<td><%= user.latest_conversation %></td>
<td class="table__more">
<%= link_to "Show details", conversations_path(user_id: user.id), class: 'table__row__details button button--tertiary button--tertiary-small' %>
</td>
</tr>
<% end %>
所以我真的很想在用户循环中访问@user.latest_conversation
【问题讨论】:
标签: ruby-on-rails activerecord