Greg Schloemann
Greg Schloemann

Reputation: 11

Displaying Associated Objects in Rails Views

I am working on a rails 4 application that currently has two models User and Status. In the user model I defined the association below. Both the status and user tables are populating with information. Statuses are loading with an associated user_id

User Model

class Status < ActiveRecord::Base
   belongs_to :user
end

I have the following block in my show status view which will display the user_id and and the content of the status

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

I would like to display the user's first name instead. According the tutorial i'm taking I should be able to use this code since I have the association defined however it's returning the error below.

  <%[email protected]_name%> 

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

How can I display first_name in the controller? Do I need to define a new method for user or should the association provide?

Relevant Controller Code for Reference

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

Upvotes: 1

Views: 1381

Answers (2)

Daniel
Daniel

Reputation: 3040

I am not sure what page you are trying to display <%[email protected]_name%> this on, but this should work.

You can use the will_paginate gem:

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

add this to the view:

<%= will_paginate %>

or this should be the normal way:

def show
  @statuses = @statuses.find(params[:id])
end

Upvotes: 0

TM.
TM.

Reputation: 3741

Sees like there is no problem in your code. The error undefined method first_name for nil:NilClass means that the status object not associated with user or user have no field first_name. Try following code:

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

Upvotes: 1

Related Questions