Z
Z
zggb2015-02-13 11:36:29
Ruby on Rails
zggb, 2015-02-13 11:36:29

Associations in polymorphic relationships?

Hello!
Available

class Location < ActiveRecord::Base
  belongs_to :locatable, polymorphic: true

class RealEstate < ActiveRecord::Base
  has_one :location, as: :locatable, dependent: :destroy

If RealEstate is clearly set in the controller
@real = RealEstate.find(params[:id])
Then the view associations
@real.location.address
work fine
The problem occurs when the controller
@user = current_user
@real = @user.real_estates

or
@real = RealEstate.all
and partials are used,
<%= render @users %>
<%= render partial: '/real_estates/real_estate', collection: user.real_estates %>

Then, the usage
<%= real_estate.location.address %>
throws an error undefined method `address' for nil:NilClass
although, if left
<%= real_estate.location %>
, the object will be shown in the view as Location:0x007fd2c9d37018
How to correctly access the parameters of the Location object? Thank you in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Dyachuk, 2015-02-13
@zggb

You are deceiving us or yourself somewhere.
Ruby is very good at distinguishing between objects of different classes. Rare are the cases when Location:0x007fd2c9d37018 suddenly becomes nil.
However, if you're rendering a collection, it's possible that the collection has an estate with a location of nil, which is causing the error.
if you use a construct like
or
you can easily find the object you are looking for
On the other side, so that this does not happen, validate
so that the data is always in a valid state

V
Viktor Vsk, 2015-02-13
@viktorvsk

Do you have an address for sure - a simple active record attribute?
Something similar happens with associations when, for example, you want to access a non-existent attribute through them, but which you automatically generate in method missing.
It also happens, for example, if you make a scope or just -
Location.select (: id), then the address method will not work.
Try to achieve this behavior in the console. See the class of the resulting object, see, as already asked - attributes. Try to pass something that doesn't work to a method that "works" (to_s, for example). For example:

def to_s
"Вот и #{address}"
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question