Reputation: 1302
I have two models:
Phonecall and Result:
class Phonecall < ActiveRecord::Base
has_many :results
end
class Result < ActiveRecord::Base
belongs_to :phonecall
end
All easy, if I do this code:
class CallsController < ApplicationController
def index
@phonecalls = Phonecall.order('datetime DESC').all
end
end
and in view:
<% @phonecalls.each do |ph| %>
<%= ph.results.id %>
<% end %>
I have an error:
undefined method `id' for #<ActiveRecord::Associations::CollectionProxy []>
What am I doing wrong? I try to get property of Result object that in relation with my Phonecall object.
Upvotes: 2
Views: 6060
Reputation: 9173
When you are doing ph.results it returns a ActiveRecord Relation and not a single record so you can't call method id on it. You need to use some logic to select a single result record from this relation.
If you want to display all the ids of results then you'll have to loop through all the results and then display them individually like this:
- @phonecalls.each do |ph|
- ph.results.each do |r|
= r.id
Upvotes: 6