Reputation: 2889
This is my nested_form:
..
...
54 <div>
55 <h2> Address </h2>
56 <%= f.fields_for :address do |address_form| %>
57 <%= address_form.text_field :country %>
58 <% end %>
59 </div>
60
61 <div>
62 <h2> Participants </h2>
63 <%= f.fields_for :participants do |participant_form| %>
64 <%= participant_form.text_field :name %>
65 <%= participant_form.link_to_remove "Remove this participant" %>
66 <% end %>
67 <p><%= f.link_to_add "Add a participant", :participants %></p>
68 </div>
...
..
Now when I visit my model/new page it does not render any fields for address or participants.
This is my model:
1 class CompetitionEntry < ActiveRecord::Base
2 has_many :participants
3 has_one :address
4 has_many :music_programs
5
6 accepts_nested_attributes_for :address
7
8 accepts_nested_attributes_for :participants, :music_programs,
9 :allow_destroy => true,
10 :reject_if => :all_blank
11 end
This is my controller:
16 def new
17 @competition_entry = CompetitionEntry.new
18 end
Why is it happening ? did I miss something?
Upvotes: 0
Views: 1896
Reputation: 23
If its has_one
relationship then the proper way to create is not
@competition_entry.address.build
it is
@competition_entry.build_address
Upvotes: 1
Reputation: 1250
Into your CompetitionController use the builder like here:
def new
@competition_entry = CompetitionEntry.new
@competition_entry.build_address
@competition_entry.participants.build
@competition_entry.music_programs.build
end
Also, builder could doesn't know about attributes you want to transfer from the nested form into controller.
Put this into your controller.
def competition_entry_params
params.require(:competition_entry).permit(<<competition_entry_attributes>>, address_attributes: [:country], participants_attributes: [:name], music_programs_attributes: [:something, :something_else])
end
And then use this into actions create and/or update
@competition_entry = CompetitionEntry.new(competition_entry_params)
Hope this will help.
Upvotes: 0
Reputation: 15089
Well, you have to use the build
method to instantiate blank nested objects, so the view could render something.
def new
@competition_entry = CompetitionEntry.new
@competition_entry.address.build
@competition_entry.participants.build
end
You can even use a loop to create more than one associated object. Like 3.times {@competition_entry.participants.build}
.
Upvotes: 1