茧添加关联,如何限制关联数量 [英] Cocoon add association, how to limit number of associations
问题描述
我正在创建一个使用Ruby/Rails/HAML存储卡的系统-在这种情况下,有一个Card类具有很多颜色(这也是一个类).创建和编辑卡片时,我使用的是Cocoon gem,可以动态添加颜色关联.
I am creating a system that stores cards using Ruby/Rails/HAML - In this case there is a Card class that has many Colours (this is also a class). When creating and editing a card I am using the Cocoon gem to allow me to dynamically add colour associations.
我遇到的问题是在Card模式中,一张卡被限制为最多只能有5种颜色.然而,该界面允许添加无限的颜色,从而导致错误.
The problem I am having is that in the Card model, a card is limited to having a maximum of 5 colours. Yet the interface allows adding of unlimited colours resulting in an error.
Cocoon中是否有一种方法可以限制可以添加到表单的关联数,从而不超过此限制?
Is there a way in Cocoon to limit the number of associations that can be added to a form, so that this limit is not exceeded?
这是添加/编辑卡的表单的代码
This is the code for a form to add/edit a Card
= simple_form_for @card, multipart: true do |c|
= c.input :name, label: "Name of the card"
= c.input :cost, label: "Cost of the card"
#colours
= c.simple_fields_for :colours do |colour|
= render "colour_fields", f: colour
.links
= link_to_add_association 'add colour', c, :colours
这是colour_fields表单
And this is the colour_fields form
.nested-fields
= f.input :value, as: :select, collection: Colour::VALUES, selected: f.object.value, include_blank: false
= link_to_remove_association "remove colour", f
谢谢.
推荐答案
我会为此使用javascript.您可以绑定到在插入新项目时触发的事件:在该事件上计算有多少项目,并在需要时隐藏链接.
I would use javascript for this. You can bind to an event that is triggered upon insert of a new item: on this event count how many items there are, and hide the link if needed.
同样,在加载页面时也要这样做.
Likewise, when loading the page do the same.
所以在代码中看起来像这样:
So in code that would look like:
$(function() {
function check_to_hide_or_show_add_link() {
if ($('#colours .nested-fields:visible').length == 5) {
$('#colours .links a').hide();
} else {
$('#colours .links a').show();
}
}
$('#colours').on('cocoon:after-insert', function() {
check_to_hide_or_show_add_link();
});
$('#colours').on('cocoon:after-remove', function() {
check_to_hide_or_show_add_link();
});
check_to_hide_or_show_add_link();
});
类似的事情应该起作用.请注意,此代码未经测试:)
Something like this should work. Note this code is not tested :)
希望这会有所帮助.
这篇关于茧添加关联,如何限制关联数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!