user3794309
user3794309

Reputation: 15

Rails - Display associated data in View

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

Upvotes: 0

Views: 754

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51191

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.

Upvotes: 4

Related Questions