简体   繁体   中英

undefined method when trying to access related record

I am getting this error.

undefined method `email' for nil:NilClass

When I try to access my related model record, like this:

User Model:

has_one :facility

User Facility:

belongs_to :user

Facility controller

@adminfacilities = Facility.all

Index.html.erb

@adminfacilities.each do |facility|
  facility.user.email

I just don't get what I'm doing wrong here. Why can't I access such info?

Lots of thanks!

Because some facility.user is nil , you may use:

@adminfacilities.each do |facility|
  facility.user.try(:email)

As xdazz said, your facility.user is nil .

Maybe you should add a validation in your Facility model

validates_presence_of :user

And a dependency for destroy

belongs_to :user, :dependent => :destroy

You probably have a Facility that does not have a user assigned to it in the foreign key, and when the foreach loop reaches that facility it finds that there is no user assigned, therefore, it cannot return the user's attribute you are looking for, in this case, email .

Check your database Facility table, there will probably be a user_id that is nil .

The code itself looks okay.

I think the reason is you are using development mode, and have not create correct association data.

Suggest you to check data again to see if any facility record doesn't have user_id.

Also it's strongly recommended to add validation as per ForgetTheNorm said.

some respective Facility don't have user so it is return nil.

Then from user table u or trying to access email. so it through exception of nil:NilClass(User nilclass)

we can write some best understanding code like this

facility.user ? facility.user.email : nil # it will facility user is there if user return then it will give user email else it return nil

(or)

facility.user.try(:email)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM