stevec
stevec

Reputation: 52837

How to avoid saving nil/blank in accepts_nested_attributes_for when displaying set number of fields for has_many association?

My question is an edgecase of how to avoid saving empty records on a nested rails form. I have a simple has_many, where a user can have a maximum of 5 job titles.

# user.rb
has_many :job_titles
validates_length_of :job_titles, maximum: 5
accepts_nested_attributes_for :job_titles, 
  allow_destroy: true,
  :reject_if => proc { |att| att[:name].blank? }

# job_titles.rb
belongs_to :user
validates_associated :user

The proc should remove any blanks, but they get created anyway (!) since I have this in the users_controller, which is used to ensure there are always 5 form fields presented in the view:

# users_controller.rb
num_job_titles = @user.job_titles.count 
(5-num_job_titles).times { @user.job_titles.build }

With this, the blanks keep appearing in the database even before the form is submitted, since the previous code builds those blank records, and the model validation seems to allow it for some reason - I didn't expect it to.

Question

How can I ensure 5 fields are displayed for 5 different associated records (job titles), and ensure blank job titles aren't saved as records to the database?

Upvotes: 0

Views: 236

Answers (0)

Related Questions