Search code examples
ruby-on-railsrubyfields-for

Fields_for build repeating itself every time I update


I'm having a stupid problem I don't know how to solve.

Im using fields_for , and every time I edit, the build is done again, and I get repeated attributes. I only want sponsors built if it's the first time created/updated only, otherwise I would like them just updated.

My view

<%= f.input :sponsored %>
<%= f.fields_for :sponsors do |sponsor| %>   
  <%= sponsor.input :name, placeholder: "Marca", label: "Marca(s)" %>
  <%= sponsor.input :description, placeholder: "Descripción de la marca", label: "Descripción" %>
  <%= sponsor.input :web, placeholder: "Web" %>
  <%= sponsor.input :facebook, placeholder: "Facebook" %>
  <%= sponsor.input :twitter, placeholder: "Twitter" %>
  <%= sponsor.input :sponsored_avatar, placeholder: "Avatar" %>
<% end %>

Photos Controller

def edit
  @photo = Photo.friendly.find(params[:id])
  @photo.sponsors.build
end

Thanks


Solution

  • The point in your code is, when Photo.friendly.find(params[:id]) have some sponsor already created and then when you @photo.sponsors.build, you are adding an empty sponsor, so, you need to build only when a Photo.friendly has not a sponsor, I think this can help you

    def edit
      @photo = Photo.friendly.find(params[:id])
      @photo.sponsors.build unless @photo.sponsors.any?
    end