0
votes

I don't understand why I can't navigate through my models with activerecord.

I have a User model that has_one profile (actually, the details of a user)

class User < ActiveRecord::Base
  has_one :profile, :dependent => :destroy 
end

A model Profile that belongs_to User and City

class Profile < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
end

And a model City that has_many Profiles

class City < ActiveRecord::Base
  belongs_to :country
  has_many :profiles  
end

In my user_controller, I can access the profile like this:

@user = User.find(params[:id])
logger.info(@user.profile.inspect)

But I can't go deeper like this:

@user = User.find(params[:id])
logger.info(@user.profile.city.inspect)

Returns

undefined method `city' for nil:NilClass

What I want to get is the name of the City from the city_id stored in the Profile model. Does someone can explain to me what I do wrong? Thanks

1
What is the result of @user.profile.inspect ? I think it is nil.Rahul Tapali
Can you confirm that @user has a profile? The relationships all look good, but if the user doesn't actually have a profile in the database then you will get the above error.rocket scientist
The city_id field of Profile was null... anyway, I still have an error: undefined method city' for #<Profile:0x00000003ef3870>`Gozup

1 Answers

2
votes

It is because you don't have Profile for that User (i.e.) @user.profile is nil. So you need to first create profile for user and do @user.profile.city. It will work. If you think profile may be nil for some record still you want to get city for records which have profile then you can use try.

    @user.profile.try(:city)