【问题标题】:Dynamic has_many through creation with tagging select2通过使用标记 select2 创建动态 has_many
【发布时间】:2019-11-15 16:12:03
【问题描述】:

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

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"]

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

【问题讨论】:

  • 应该是has_many :recipe_equipmentsaccepts_nested_attributes_for :recipe_equipmentshas_manyassociations 应始终为复数形式。
  • 设备是设备的复数
  • 是的,你的权利。 (捂脸)。

标签: ruby-on-rails jquery-select2


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多