Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails has_one association fields_for form not displaying

I have a Meeting model:

class Meeting < ActiveRecord::Base
  has_one :location, :class_name => "MeetingLocation", :dependent => :destroy
  accepts_nested_attributes_for :location

Then I have a MeetingLocation model:

class MeetingLocation < ActiveRecord::Base
  belongs_to :meeting

My new meeting form:

<%= form_for @meeting do |f| %>
  <%= f.label :location %>
  <%= fields_for :location do |l| %>
    Name <%= l.text_field :name %>
    Street <%= l.text_field :street %>
    City <%= l.text_field :city, :class => "span2" %>
    State <%= l.select :state, us_states, :class => "span1" %>
    Zipcode <%= l.text_field :zip, :class => "span1" %>
  <% end %>

When I view the new meeting form, the location fields are blank! I only see the location label but no other location fields. I've been looking for an explanation for the past 3 hours, found lot's of similar issues but no luck.

Thanks.

like image 549
absolutskyy Avatar asked Jun 14 '12 22:06

absolutskyy


1 Answers

The reason the location fields aren't displaying is that when you create a new meeting with @meeting = Meeting.new, this meeting does not yet have an associated MeetingLocation. If you call @meeting.location, you would get nil. For this reason, the form doesn't display fields for the location.

To fix this, you should call @meeting.build_location after creating a new meeting. That will associate the new meeting with a blank location.

EDIT: try changing fields_for to f.fields_for

like image 134
cdesrosiers Avatar answered Sep 28 '22 01:09

cdesrosiers