Reputation: 1754
I know this question have asked countless times, but I didn't find anyone with the issue I have.
It may be important to note that this is a single resource.
models/basic.rb
class Basic < ApplicationRecord
has_many :social_networks
accepts_nested_attributes_for :social_networks, reject_if: :all_blank, allow_destroy: true
mount_uploader :logo, LogoUploader
end
models/social_network.rb
class SocialNetwork < ApplicationRecord
belongs_to :basic
end
controllers/basic_controller.rb
def show
end
def new
@basic = Basic.new
@basic.social_networks.build
end
def edit
end
private
# Use callbacks to share common setup or constraints between actions.
def set_basic
@basic = Basic.first
end
# Never trust parameters from the scary internet, only allow the white
list through.
def basic_params
params.require(:basic).permit(:base_title, :resume, :logo, social_networks_attributes: [:id, :name, :url])
end
end
views/basics/_form.html.erb
<%= form_with(model: @basic, local: true, url: basics_path) do |f| %>
<div id="social_networks">
<%= f.fields_for :social_networks do |sn| %>
<%= render 'social_networks', f: sn %>
<% end %>
<div class="links">
<%= link_to_add_association 'Ajouter', f, :social_networks %>
</div>
</div>
<%= end %>
_social_network_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.label :name %>
<%= f.text_field :name, placeholder: 'Nom' %>
</div>
<div class="field">
<%= f.label :url %>
<%= f.text_field :url, placeholder: 'Lien' %>
</div>
<div class="links">
<%= link_to_remove_association 'Supprimer', f %>
</div>
</div>
As said in the question title, my form works fine and saves up the elements I fill in correctly. However, when I want to edit, I get an error saying that it can't find a template for the resource (it waits for a file named _social_networks.html.erb
). When I add it (and let it blank), I get the form as if I want to create some new resources.
What did I do wrong?
Thank you in advance
Upvotes: 2
Views: 191
Reputation: 3005
You wrote
<%= render 'social_networks', f: sn %>
But your view is _social_networks_fields.html.erb
Cant you just rename _social_networks_fields.html.erb to _social_networks.html.erb?
Also change your add association link:
<div class="links">
<%= link_to_add_association 'Ajouter', f, :social_networks, :partial => 'social_networks' %>
</div>
Or just use
<%= render 'social_networks_fields', f: sn %>
And you don't need the social_networks.html.erb
Upvotes: 3