Search code examples
ruby-on-railsruby-on-rails-4nested-formsfields-for

(Rails 4.0.1) "has_one" nested model not working


After following few different guides I am still getting troubles with nesting one model addr within form of other hotel. I wasable to get working form before which created db row for hotels, but didn't one for addr. After I added @hotel.addrs.build to my controller, I am getting an error

undefined method `build' for nil:NilClass on this line.

My code:

hotels.rb

class Hotel < ActiveRecord::Base
    has_one :addrs
    accepts_nested_attributes_for :addrs
end

addr.rb

class Addr < ActiveRecord::Base
    belongs_to :hotel
end

hotels_controller.rb

def new
    @hotel = Hotel.new
    @hotel.addrs.build
end
...
def hotel_params
    params.require(:hotel).permit(:name, :rate, addrs_atributes: [:street, :build])
end

routes.rb

resources :hotels do
    resources :addr
end

_form.erb.html

... </div>
<%= fields_for :addr do |l| %>
    Street <%= l.text_field :street %><br>
    No. <%= l.number_field :build %>
<% end %>
<div class="actions">
    <%= f.submit %>
</div>

Please suggest what could be wrong here. Thanks.


Solution

  • it should be

     has_one :addr
    accepts_nested_attributes_for :addr
    

    in controller new action

     @hotel.build_addr
    

    in hotel_params

     params.require(:hotel).permit(:name, :rate, addr_atributes: [:street, :build])
    

    in view

    <%= f.fields_for :addr do |addr|%> 
    
    <%end%>