Answer the question
In order to leave comments, you need to log in
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
@real = RealEstate.find(params[:id])
@real.location.address
@user = current_user
@real = @user.real_estates
@real = RealEstate.all
<%= render @users %>
<%= render partial: '/real_estates/real_estate', collection: user.real_estates %>
<%= real_estate.location.address %>
<%= real_estate.location %>
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question