我很生气我问这个,因为它应该是显而易见的。但我有问题。我正在尝试在索引中显示引用模型的属性。
Rails 4.0.0
ruby 2.0.0p247
应用程序/模型/unit.rb
class Unit < ActiveRecord::Base
belongs_to :building
end
应用程序/模型/building.rb
class Building < ActiveRecord::Base
has_many :units
end
在控制台中:
Loading development environment (Rails 4.0.0)
2.0.0-p247 :001 > unit = Unit.find(3)
Unit Load (4.1ms) SELECT "units".* FROM "units" WHERE "units"."id" = ? LIMIT 1 [["id", 3]]
=> #<Unit id: 3, number: "APT 10", bed: "2", bath: "2", sqft: "300", amenities: "Stuff", building_id: 3, created_at: "2013-10-15 04:17:45", updated_at: "2013-10-15 04:37:10">
2.0.0-p247 :002 > unit.building.street_address
Building Load (0.5ms) SELECT "buildings".* FROM "buildings" WHERE "buildings"."id" = ? ORDER BY "buildings"."id" ASC LIMIT 1 [["id", 3]]
=> "4564 Jones Ave"
2.0.0-p247 :003 >
在默认 index.html.erb 中只有一处更改:
<% @units.each do |unit| %>
<tr>
<td><%= unit.number %></td>
<td><%= unit.bed %></td>
<td><%= unit.bath %></td>
<td><%= unit.sqft %></td>
<td><%= unit.amenities %></td>
<td><%= unit.building.street_address %></td>
<td><%= link_to 'Show', unit %></td>
<td><%= link_to 'Edit', edit_unit_path(unit) %></td>
<td><%= link_to 'Destroy', unit, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
我所做的唯一更改是添加“.street_address”。如果我添加它,我会收到一条错误,即 street_address 不是已定义的方法。如果我移除它,导轨将清楚地显示该单元已连接到建筑物。我该怎么办?