在Rails视图中显示关联对象

时间:2014-01-13 01:46:14

标签: ruby-on-rails ruby ruby-on-rails-4

我正在开发一个rails 4应用程序,目前有两个模型User和Status。在用户模型中,我在下面定义了关联。状态表和用户表都填充了信息。状态正在加载相关的user_id

用户模型

class Status < ActiveRecord::Base
   belongs_to :user
end

我的show status视图中有以下块,它将显示user_id和状态的内容

<% @statuses.each do |status| %>
   <div class="status">
   <strong> <%=status.user_id%></strong>
   <p> <%=status.content%></p>

我想显示用户的名字。根据我正在使用的教程,我应该可以使用此代码,因为我已经定义了关联,但是它返回了下面的错误。

  <%=@status.user.first_name%> 

  Error      
  #==>undefined method `first_name' for nil:NilClass

如何在控制器中显示first_name?我是否需要为用户定义新方法,还是应该提供关联?

相关控制器代码供参考

class StatusesController < ApplicationController


  before_action :set_status,:set_user, only: [:show, :edit, :update, :destroy]

  # GET /statuses
  # GET /statuses.json

 def index
    @statuses = Status.all
  end

  # GET /statuses/1
  # GET /statuses/1.json

  def show
    puts "debug msg #{@status.inspect}"
  end



  # GET /statuses/new
  def new
    @status = Status.new
  end

  # GET /statuses/1/edit
  def edit
  end

  # POST /statuses
  # POST /statuses.json

...
...
...

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_status
      @status = Status.find(params[:id])
      puts "in set status"
    end

    def set_user
      @status.user = User.find_by(@status.user_id)
    end



    # Never trust parameters from the scary internet, only allow the white list through.
    def status_params
      params.require(:status).permit(:content, :user_id)
    end
end

2 个答案:

答案 0 :(得分:1)

看起来代码中没有问题。错误undefined method first_name for nil:NilClass表示与statususer无关的user对象没有字段first_name。请尝试以下代码:

<% @statuses.each do |status| %>
   <div class="status">
   <strong> <%=status.user.try(:first_name) %></strong>
   <p> <%=status.content%></p>

答案 1 :(得分:0)

我不确定您尝试在<%=@status.user.first_name%>显示哪个页面,但这应该有效。

您可以使用will_paginate gem:

def show
  @statuses = @statuses.paginate(page: params[:page])
end

将此添加到视图中:

<%= will_paginate %>

或者这应该是正常的方式:

def show
  @statuses = @statuses.find(params[:id])
end
相关问题