0

My nested attribute form is adding unwanted fields automatically each time I save my regular form.

How do I prevent from adding an extra field after saving?

registrations_controller.rb controller

def edit
  @user = User.find(current_user.id)
  @profile = Profile.new
  @user.businesses.build
end 

business.rb model

class Business < ActiveRecord::Base
  belongs_to :users
end

user.rb model

class User < ActiveRecord::Base
  has_many :businesses
end

view page

<%= form_for @user, :html => {:multipart => true} do |f| %>
  <%= f.fields_for :businesses do |builders| %>
    <%= builders.text_field :name %>
  <% end %>

  <%= f.submit "Save" %>
<% end %>

At first it shows a single empty field, and then when I press save, it adds another one, even though if its blank or not. I just want to keep one field for now and not automatically add another one.

1 Answer 1

1

Try:

class User < ActiveRecord::Base
  has_many :businesses
  accepts_nested_attributes_for :businesses, allow_destroy: true, reject_if: lambda { |b| b[:name].blank? }
end

UPDATE:

@user.businesses.build if @user.businesses.empty?
Sign up to request clarification or add additional context in comments.

4 Comments

it still adds an extra field when saving record
It should reject businesses with empty name. Updated.
Oh its almost there! But why is it that if I have a value saved in the field, I can't save an empty field anymore if I decide to leave the field empty, after saving it?
If u want to add another field - use link_to_add and link_to_remove helper methods on the form builder. And remove reject_if if u want to save empty values in new fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.