首页 > 解决方案 > 通过使用标记 select2 创建动态 has_many

问题描述

我有一个配方模型,它通过配方设备设置如下:

class Recipe < ApplicationRecord
  has_many :recipe_equipment, dependent: :destroy
  has_many :equipment, through: :recipe_equipment
  accepts_nested_attributes_for :recipe_equipment
end

class Equipment < ApplicationRecord
    has_many :recipe_equipment
    has_many :recipes, through: :recipe_equipment
end

class RecipeEquipment < ApplicationRecord
  belongs_to :recipe
  belongs_to :equipment
end

一切都非常简单。然后在我的食谱表单中,我使用 select2 并启用了 tags 选项,这里是输入:

<div class="form-group">
  <%= form.label :equipment_ids, "Equipment Needed" %>
  <%= form.collection_select :equipment_ids, Equipment.all.order(:name), :id, :name, {:selected => recipe.recipe_equipment.map(&:equipment_id)}, { multiple: true } %>
</div>

和标准的 select2 初始化:

$('#recipe_equipment_ids').select2({
    width: '100%', 
    maximumSelectionLength: 10,
    tags: true});

所以这一切都按预期工作,除了输入新设备时,它作为文本而不是 id 提交(因为尚未创建设备并且没有 ID)

"equipment_ids"=>["", "7", "3", "Wok"]

因此,在调用控制器中的创建/更新之前寻找一种处理参数数组的方法,如果新设备不存在则创建新设备。不知道该怎么做。

标签: ruby-on-railsjquery-select2

解决方案


所以在我发布后马上想通了,但我想我会为其他人发布答案。此外,这可能不是最好的解决方案,但它确实完成了工作并限制了对数据库的额外查询

所以我最终覆盖了 recipe.rb 文件中设备 ID 的默认访问器。因为它是作为潜在整数和字符串的混合出现的,所以检查它是否已经不是整数,然后使用 find_or_create_by!方法来创建一个新设备的名称。然后将新的 id 传递给一个数组并将其传递给超级。

def equipment_ids=(value)
  equip = []
  value.reject!(&:empty?).each do |e|
    equip << (e.to_i != 0 ? e : Equipment.find_or_create_by!(name: e).id)
  end  
  super(equip)
end

推荐阅读