0

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?

stevec
  • 41,291
  • 27
  • 223
  • 311
  • 1
    You could use this gem https://github.com/nathanvda/cocoon. It will allow you to dynamically create the relationships. With the condition of 5 max, I'm sure there's a way to limit the number of times a user can add more, but if you're using Rails views I would definitely check this out – Int'l Man Of Coding Mystery Feb 26 '21 at 15:07
  • @Int'lManOfCodingMystery thanks, I don't use cocoon yet, but I'll definitely have to investigate – stevec Feb 26 '21 at 16:45
  • Ya, I'm not 100% if it will fit your needs but it's pretty useful in dealing with dynamic relationships – Int'l Man Of Coding Mystery Feb 26 '21 at 16:48

0 Answers0