Rails 4.2.1,Ruby 2.2.1
宝石:simple_form
,cocoon
以下是有关系的模型:
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
图库应该有6张照片,这就是我使用after_initialize
回调来构建6个photo
对象的原因。
的观点:
用户表单
.form-inputs
= f.simple_fields_for :galleries do |gallery|
= render 'gallery_fields', f: gallery
.links
= link_to_add_association 'add gallery', f, :galleries
图库字段
.nested-fields
= f.simple_fields_for :photos do |photo|
= render 'photo_fields', f: photo
= link_to_remove_association 'remove photos', f
br
照片栏
.nested-fields
= f.input :size
如果我在第一次输入中输入正确的值而在其他输出中输入错误则验证失败后,结果将是1输入,填充正确值+ 6空输入字段,依此类推。
我该如何避免?如果用户决定拥有一张照片,我总是需要为每个画廊制作6张照片。
我在github上推送了示例应用,因此您可以重现问题https://github.com/gabyshev/cocoon_example_increasing_number_of_fields
答案 0 :(得分:0)
我认为问题是因为你有1个有效的关联记录,并且在初始化对象后你仍在构建6条记录!为避免您可以执行以下操作:
var ex = chart.yAxis[0].getExtremes();
答案 1 :(得分:0)
请勿使用after_initiazlize
。 Cocoon帮助您精确制作6个画廊。你只需要使用一点点javascript:
使用cocoon:after-insert
,您可以检查嵌套字段是否大于6,如果&gt; = 6,则$('.nested-fields')[1].remove();
。
使用cocoon:after-delete
,您可以检查嵌套字段是否小于6,如果&lt; 6,然后显示添加按钮。
我做过类似的事情,希望有所帮助:
<script>
$('.announcements').on('cocoon:after-insert', function(e, insertedItem) {
if ($('.nested-fields').length >= 10){
$('.nested-fields')[1].remove();
}
});
$('.announcements').on('cocoon:after-delete', function(e, insertedItem) {
if ($('.nested-fields').length < 10){
$('.add_fields').show();
}
});
$(document).ready(function() {
$(".add_news_button").
data("association-insertion-method", 'after').
data("association-insertion-node", 'this');
});
</script>