0

尽管我遇到了麻烦,但应该很容易回答的快速问题:

我有一个简单的 Rails 应用程序,带有一个消息('intro')选项卡,显示发送和接收的消息('intro')。我将消息从用户适当地路由到用户,并且消息的内容在用户收件箱中显示良好。但是,我无法在消息本身旁边显示与消息关联的用户的名称

我有一个用户模型:

class User < ActiveRecord::Base
    attr_accessible :name, :email, :one_liner, :password, :password_confirmation
    has_secure_password

    has_many :sent_intros, foreign_key: "sender_id", dependent: :destroy, class_name: "Intro"
    has_many :received_intros, foreign_key: "receiver_id", dependent: :destroy, class_name: "Intro"

    has_many :receivers, through: :sent_intros, source: :receiver
    has_many :senders, through: :received_intros, source: :sender

        ...

,一个介绍(消息)模型:

class Intro < ActiveRecord::Base
  attr_accessible :content, :receiver_id, :sender_id

  belongs_to :sender, class_name: "User"
  belongs_to :receiver, class_name: "User"

  ...

这是用户控制器的相关代码:

class UsersController < ApplicationController
  before_filter :signed_in_user, only: [:index, :edit, :update, :destroy]
  before_filter :correct_user, only: [:edit, :update]
  before_filter :admin_user, only: :destroy

  def show
    @user = User.find(params[:id])
    @intro = Intro.find(params[:id])

    @sent_intros = current_user.sent_intros.paginate(page: params[:page])
    @received_intros = current_user.received_intros.paginate(page: params[:page])
  end
  ...

我的 .erb 显示页面:

<% provide(:title, @user.name) %>
<div class="row">
    <aside class="span4">
        <section>
            <h1>

                <%= @user.name %>
            </h1>
        </section>
    </aside>
    <div class="span8">
        <% if@user.received_intros.any? %>
            <h3>Received intros (<%= @user.received_intros.count %>)</h3>
            <ol class="intros">
                <%= render @received_intros %>
            </ol>
            <%= will_paginate @received_intros %>
        <% end %>

        <% if@user.sent_intros.any? %>
            <h3>Sent intros (<%= @user.sent_intros.count %>)</h3>
            <ol class="intros">
                <%= render @sent_intros %>
            </ol>
            <%= will_paginate @sent_intros %>
        <% end %>
    </div>
</div>

所以我关心这个页面的 <%= render @received_intros %> 和 <%= render @sent_intros %> 行

目前,它显示以下内容(没有关联用户的介绍内容):

在此处输入图像描述

如何将这些用户名添加到各自的介绍中?谢谢!

4

1 回答 1

0

看起来您正在根据与控制器操作中的用户相同的 ID 查找 Intro。由于它是第二次查找的,它覆盖了@user 变量。这是你的代码:

@user = User.find(params[:id])
@intro = Intro.find(params[:id])

我猜您可能希望第二行类似于 params[:intro_id],但如果没有看到链接到该页面的视图代码以及可能是您的路由文件,则不能完全确定。

于 2012-07-04T18:29:37.687 回答