Does Accepts_nested_attributes_for stop rendering my subform?

I have a connection between two models: business and address. where the business has a registered_address. I did it as follows.

class Business < ActiveRecord::Base has_one :registered_address, :class_name => "Address", :foreign_key => :business_registered_address_id accepts_nested_attributes_for :registered_address end class Address < ActiveRecord::Base belongs_to :business end 

This association works great for my purposes. When I put out a form using:

 = form_for @business do |form| = form.inputs :name => "Registered address" do = form.fields_for :registered_address do |address| = address.input :postcode = address.input :line_1 = address.input :line_2 = address.input :line_3 = address.input :town = address.input :county 

Nothing is displayed, just an empty set of fields.

When I comment out the line accepts_nested_attributes_for in the business model, it displays (but does not save) all the fields correctly.

Can anyone see what I'm doing wrong?

thanks

+4
source share
2 answers

Write in your controller for this action ( new , as I think)

 def new @business = Business.new @business.build_registered_address ... end 

or in your form @business.registered_address.new

 = form_for @business do |form| = form.inputs :name => "Registered address" do = form.fields_for :registered_address, @business.registered_address.new do |address| = address.input :postcode = address.input :line_1 = address.input :line_2 = address.input :line_3 = address.input :town = address.input :county 
+6
source

form.fields_for displays its block for each object in @ business.registered_adress. If your array is empty, nothing is displayed.

You can write, for example, on your controller:

 @bussines.registered_address.new 

Then the application will display the whole form

Hope this helps

+1
source

Source: https://habr.com/ru/post/1343770/


All Articles