Question

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.

Was it helpful?

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%>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top