Search code examples
formsruby-on-rails-4associationsparentfields-for

In RoR, f.fields_for is rendering as nothing


I’m using Rails 4.2.7. In my model I have

class MyObject < ActiveRecord::Base
    …
  belongs_to :address, :autosave => true, dependent: :destroy

  accepts_nested_attributes_for :address, :my_object_times

and the address model

class Address < ActiveRecord::Base
  belongs_to :state
  belongs_to :country
  ...
  has_one :my_object

end

I want to write a form that will allow me to build both the child and parent objects, so I tried

<%= form_for @my_object, :url => my_objects_create_path, :remote => true do |f| %>

  <div class="field">
    <%= f.fields_for :address do |addr| %>
    <%= addr.label :address %> <span name="my_object[address]_errors"></span><br>
    City: <%= addr.text_field :city %>
    <%= addr.select :state, options_for_select(us_states.collect{|s| [ s.name, s.id ]}), {:prompt => "Select State"} %>
    <%= country_code_select('my_object[address]', 'country_id',
              [[ 'US', 'United States' ], [ 'CA', 'Canada' ]],
              {:include_blank=>true, :selected => @default_country_selected.id},
              {:class=>'countryField'}
              ) %>
    <% end %>
  </div>

but the above is rendered as only

<div class="field">
</div>

How do I adjust things so that my fields render AND I'm able to create my object in my controller using

my_object = MyObject.new(params) 

Edit: Per the answer given, I tried

@my_object.address.build

from teh controller action taht rendres the form, but got the erorr

undefined method `build' for nil:NilClass

Solution

  • #this is in form loading class

    def new
        @myobject = MyObject.new
        @myobject.address = Address.new
    end
    

    #Now you can use nested attribute for Address

    <%=form_for(@myobject) do |f|%>
    <%=f.fields_for :address do |a|%>
        Your form fields here
        <%end%>
    <%end%>
    

    #this is create def

    def create 
    @myobject = MyObject.new(myobject_params)
    @myobject.save
    end
    

    #in params

    def myobject_params
    params.require(:myobject).permit(:some, :key,:of, :myobject, :address_attributes[:address, :attribute])
    end
    

    #this should work