0

Here are my models:

class Account < ActiveRecord::Base
has_many :users

# Data name:string

class User < ActiveRecord::Base
belongs_to :account

So when I try to call for the name of the Account associated to User in view index.html.erb:

<%= user.account.name %>

I get error

NoMethodError in Users#index
undefined method `name' for nil:NilClass

Does it have to do with my controller?

def index
@users = User.all
end

1 Answer 1

4

Apparently, at least one of your User records doesn't have its Account associated, so user.account returns nil. Answering directly to your question: No it has nothing to do with your controller (controller code is correct).

If you let users without accounts exist, you can avoid error with Object#try method:

<%= user.account.try(:name) %>

This method returns actual account name if it's present. Otherwise (i.e. if user.account returns nil) it returns nil.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. Can I ask another question, if I must have many users without Account is there a way to display this code without error?
@user3794309 I edited to answer your second question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.