1

I have developed rails app with three classes.

class Location < ActiveRecord::Base
    has_many :observations

end

class Observation < ActiveRecord::Base
  belongs_to :location
  has_one :rainfall
  has_one :temperature
  has_one :winddirection
  has_one :windspeed
  has_one :dewpoint

end


class Rainfall < ActiveRecord::Base
  belongs_to :observation

end

Railfall is related to Observation through an observation_id and Observation is related to Location through a location_id.

If i go to console and type something like: Location.all.first.observations.first.rainfall.value it returns me the data in value column of rainfall

However when i want to combine all the info in rails in a table and in my view/location/index.html.erb i put:

<tbody>
    <% @locations.each do |location| %>
      <tr>

        <td><%= location.name %></td>



        <% unless @observations = nil %>

        <% location.observations.each do |obs| %>
        <td><%= obs.name %></td>

        <% unless @rainfalls = nil %>
        <td><%= obs.rainfalls.value %></td>


    <% end %>
    <% end %>

I get an error:

    undefined method `rainfalls' for Observation:0x00000004219068>

I have spent the last 5 hours trying just about everything i can and am getting a tad frustrated....any ideas?

Note i have a locations controller but observation and rainfall were generated as models, so do not. Am thinking i need to add something to my location controller, just can't work out what, and I am unsure why it returns the correct data in console, just no in app.

2
  • 1
    It should be rainfall as it's a has_one relationship Commented Apr 22, 2015 at 7:25
  • 1
    Just an Observation of my own, do you really need all those relations? Seems like all of those has_one relations could just be fields in the Observation model. Commented Apr 22, 2015 at 8:56

2 Answers 2

5

Observation.has_one :rainfall, so it should be:

<%= obs.rainfall.value %>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the suggestion, the error now changes to: undefined method `value' for nil:NilClass
use <%= obs.rainfall.try(:value) %>
@user2851268 that means there's no rainfall associated with at least one of observations records. Either make sure there is always rainfall associated, or follow Nithin's suggestion.
Thanks Nithin that works perfectly!! Could you possibly explain why the .try(:value) worked? Just saw Marek's comment, thanks everyone, make sense now.....you have saved me hours more hair pulling. thanks!!
@user2851268 try(:value) calls method value if object is present, returns nil otherwise.
0

You have one to one relationship, not has_many. Replace

 <%= obs.rainfalls.value %>

by

 <%= obs.rainfall.value %>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.