Rails显示表数据

时间:2015-04-22 07:22:12

标签: ruby-on-rails view

我开发了三个类的rails app。

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通过observation_id与观察相关,而观察通过location_id与位置相关。

如果我去控制台并键入以下内容: Location.all.first.observations.first.rainfall.value 它返回降雨量值栏中的数据

但是,当我想在表格和我的视图/ location / index.html.erb中组合rails中的所有信息时,我把:

<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 %>

我收到错误:

    undefined method `rainfalls' for Observation:0x00000004219068>

我花了最近5个小时尝试了我能做的一切,并且让我感到沮丧....任何想法?

注意我有一个位置控制器但观察和降雨是作为模型生成的,所以不要。我想我需要在我的位置控制器上添加一些东西,但是不能解决问题,我不确定为什么它会在控制台中返回正确的数据,只是在app中没有。

1 个答案:

答案 0 :(得分:0)

你有一对一的关系,而不是has_many。取代

 <%= obs.rainfalls.value %>

通过

 <%= obs.rainfall.value %>