Bharath Mg
Bharath Mg

Reputation: 1127

Rails Show from two tables not working

I have two models , Place and Address. And the models relationships are,

In Place, has_one :address , :dependent => :destroy In Address, belongs_to :place.

In new form in Places Controller I can add the fields to Address without any problem using fields_for :address in form.

But when showing , a Place details, I cannot get the Address details of that place. I don't know where I am doing a mistake.

In show.html.erb in Places Controller, I have,

<% @places.each do |place| %>
<p>
 <b>Max people:</b>
 <%=h place.max_people %>
</p>

<p>
 <b>Street:</b>
 <%=h place.address.street %>
</p>
<p> City: </b>
 <%=h place.address.city %>
</p>
<p> Pincode: </b>
   <%=h place.pincode %>
</p>
<% end %>

So , in PlacesController ,

def show
@userid=session[:userid]
@places = Place.find(:all , :conditions => ["user_id = ?", @userid])

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @place }
end
end

which displays all the Place details properly but not Address details. I have searched through SO for finding my mistake but all I found was problem with forms. In my case, new form working properly, but not show.

Error is ,

  NoMethodError in Places#show

 Showing app/views/places/show.html.erb where line #9 raised:

 undefined method `street' for nil:NilClass

In console,

  `Place.last.address.street` gives me correct data.

Am I missing something? Thanks.

Upvotes: 0

Views: 69

Answers (2)

Ameen
Ameen

Reputation: 84

@Valery is right. All places may not have an address object.

Try this:

<% @places.each do |place| %>
    <% next unless place.address.present? %>
    <p>
        <b>Street:</b>
        <%= place.address.street %>
    </p>
<% end %>

Upvotes: 0

Valery Kvon
Valery Kvon

Reputation: 4496

Be sure that all places have an address object. And you can avoid exceptions using .try()

<%=h place.address.try(:street) %>

<%=h place.address.try(:city) %>

So, if the place.address is nil, nothing will be rendered.

Upvotes: 1

Related Questions