Why is Rails displaying memory addresses on my page?
My view:
<h1><%= @territory.name %></h1>
<%= link_to 'List of Territories', territories_path %>
<%= render 'shared/address_form' %>
<table>
<tr>
<td><strong>Name</strong></td>
<td><strong>Street</strong></td>
<td><strong>District</strong></td>
<td><strong>Note</strong></td>
<tr>
<%= @addresses.each do |address| %>
<tr>
<td><%= address.name %></td>
<td><%= address.street %></td>
<td><%= address.district %></td>
<td><%= address.note %></td>
</tr>
<% end %>
</table>
The form I render here is:
<%= form_for [@territory, @new_address] do |f| %>
<div>
<p>
<%= f.label :address %><br />
<%= f.text_area :address %>
</p>
</div>
<div class='file-wrapper'>
<%= f.submit "Submit" %>
</div>
<% end %>
Here is the territories controller, where the instance variable addresses is defined:
class TerritoriesController < ApplicationController
def index
@territories = 开发者_StackOverflow中文版Territory.all
end
def show
@territory = Territory.find(params[:id])
@new_address = @territory.addresses.build
@addresses = @territory.addresses
end
.
.
.
Why is Rails displaying
#<Address:0x7e088224>#<Address:0x7e0881d4>#<Address:0x7e088134>#<Address:0x7e088094># <Address:0x7e087ff4>#<Address:0x7e087f54>#<Address:0x7e087eb4>#<Address:0x7e087e14>#<Address:0x7e087d74>#<Address:0x7e0bce48>
after the form and before the table?
Thanks Thomas
Check your layouts (app/views/layouts/*). Most likely you have included some ERB code in the one that is being rendered with this page that displays these addresses. Is that the full code of your view?
Edit: I found your solution. Right now, you have <%= @addresses.each ... %>
. The each method runs the block on all elements, and then returns the list of elements. You do not want this code to be displayed. Remove the =
so that <%=
is just <%
You have some view code somewhere (in a layout or a view helper) that is implicitly calling the to_s
method of your Address
model instances. Look for something like <%= @address %>
.
As you have seen, the non-overridden behaviour of the to_s
method is to output the memory address of the object instance.
Those are not memory addresses. Those are instances of your Address class. If you'd override the to_s
method in that class, you'd see that output there instead. And the reason you see those object printed out is your use of <%=
. Changing this line
<%= @addresses.each do |address| %>
to this
<% @addresses.each do |address| %>
should fix it.
First: I can see no form in your view. Second: Your view looks ok.
Have a look at your layout files.
精彩评论