relationship - Ruby on Rails relation output between 2 models -
i have 2 models. first events , second cities. in events table have column called city_id. want city name on each event show view.
in events controller:
@city = city.where(:id => @event.city_id)
and in view:
<%= @city.name %>
a city has many events , event belongs city.
the output in view word city.
hm, mistake?
change code from:
@city = city.where(:id => @event.city_id)
to:
@city = @event.city
besides being longer necessary, original code returns activerecord::relation
object - lazy loaded query - collection of cities. calling @city.name
getting class name relation - 'city'. work if added .first
trigger query , first record:
@city = city.where(:id => @event.city_id).first
but stated above, lot more code necessary ;). of course, assuming set belongs_to :city
statement in event class.
Comments
Post a Comment