Bastien
Bastien

Reputation: 606

Rails Understanding Active Record Association

I have issues understanding Active Record Association. I have the following

<%= feed_item.spot.inspect %>

which gives me the following output

#<Spot id: 18, name: "XX", city: "XX", created_at: "2016-02-22 22:30:00", updated_at: "2016-02-22 22:30:00">

EDIT:

I want to get the name (XX) of the spot?

<%= feed_item.spot.name %>

does not seem to work. What should I do?

Upvotes: 0

Views: 39

Answers (1)

Tobias
Tobias

Reputation: 4663

You get this error because the spot is nil. If your spot is allowed to be nil you should test the value before.

<%= feed_item.spot.name if feed_item.spot.present? %>

If it isn't allowed to be nil add a presence validator to your feed_item model.

class YourModel < ActiveRecord::Base
  validates_presence_of :spot_id
end

With that you can be sure that spot is never nil in a fresh database.

Upvotes: 3

Related Questions