Rails 4.2.1, Ruby 2.2.1
Gems: simple_form
, cocoon
Here are the models with relations:
class User < ActiveRecord::Base
has_many :galleries, dependent: :destroy
accepts_nested_attributes_for :galleries, reject_if: :all_blank, allow_destroy: true
validates_presence_of :name
end
class Gallery < ActiveRecord::Base
belongs_to :user
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, reject_if: :all_blank, allow_destroy: true
after_initialize :make_photos
private
def make_photos
6.times { photos.build }
end
end
class Photo < ActiveRecord::Base
belongs_to :gallery
validates :size, presence: true, numericality: { only_integer: true }
end
Gallery should have exactly 6 photos, that's why I used after_initialize
callback to build 6 photo
objects.
views:
user form
.form-inputs
= f.simple_fields_for :galleries do |gallery|
= render 'gallery_fields', f: gallery
.links
= link_to_add_association 'add gallery', f, :galleries
gallery fields
.nested-fields
= f.simple_fields_for :photos do |photo|
= render 'photo_fields', f: photo
= link_to_remove_association 'remove photos', f
br
photos fields
.nested-fields
= f.input :size
If I type correct value in first input and incorrect in others after validation fail the result will be 1 input with filled correct value + 6 empty input fields and so on.
How do I avoid it? I always need to build 6 photos per gallery, if User decided to have one.
I pushed sample app on github, so you can reproduce the problem https://github.com/gabyshev/cocoon_example_increasing_number_of_fields
I think the problem is because you have 1 valid associated record, and you are still building 6 records, after object is initialized! To avoid you can do following:
def make_photos
photos.size.upto(6).each { photos.build }
end