tessad
tessad

Reputation: 1219

Display user profile_name knowing user_id

I have added an updated_by attribute to my guideline model which stores the user_id of the person who updated the guideline. I'd like to display this in my show view as the profile_name of the person who updated_by

in guidelines_controller.rb:

def update

    @guideline = Guideline.find(params[:id])


    respond_to do |format|
      if @guideline.update_attributes(params[:guideline])
        @guideline.update_attribute(:updated_by, current_user.id)

This seems to work fine and allocated the current user's id to updated_by.

def show

    @guideline = Guideline.find(params[:id])
    @created = @user.where(:id=>@guideline.updated_by).first.profile_name

Then my show view

<%= @created %>

The error is

NoMethodError (undefined method `where' for nil:NilClass):
  app/controllers/guidelines_controller.rb:137:in `show'

How can I get the profile name from the updated_by id?

Upvotes: 0

Views: 116

Answers (3)

Kevin Bedell
Kevin Bedell

Reputation: 13404

You need to call the finder as a class method rather than an object method.

@created = User.where(:id => @guideline.updated_by ).first.profile_name

Or cleaner

@created = User.find(@guideline.updated_by).profile_name

It's also possible you may need to search by @guideline.updated_by.id instead of @guideline.updated_by. In that case it would be:

@created = User.find(@guideline.updated_by.id).profile_name

Upvotes: 2

moonfly
moonfly

Reputation: 1820

The error is due to the fact that you call where on @user, not on User. Just call

@created = User.where(:id=>@guideline.updated_by).first.profile_name

Not sure if that's the only problem, but let's deal with them one-by-one.

Upvotes: 1

drewinglis
drewinglis

Reputation: 434

This line:

@created = @user.where(:id=>@guideline.updated_by).first.profile_name

should read:

@created = User.where(:id=>@guideline.updated_by).first.profile_name

where is a class method on the User model. @user (usually) refers to an instance of a user, which you haven't instantiated yet, in this case. (It is nil; that's why you're getting the NilClassError.)

An even cleaner version of this line would be:

@created = User.find(@guildeline.updated_by).profile_name

Since User.find finds the user for a given user_id.

Upvotes: 1

Related Questions