繁体   English   中英

Rails多对多关联,带有正确的验证并保存所有

[英]Rails Many-to-many association with correct validation and save all

在我的Rails 4.2.5应用程序中,我具有以下两个模型(Spell,Category),它们与关联模型(Spellcategory)具有多对多关系:

class Spell < ActiveRecord::Base
    has_many :spellcategories, class_name: "Spellcategory", foreign_key: "spell_id", dependent: :destroy
    has_many :categories, through: :spellcategories, source: :category
end

class Category < ActiveRecord::Base
    has_many :spellcategories, class_name: "Spellcategory", foreign_key: "category_id", dependent: :destroy
    has_many :spells, through: :spellcategories, source: :spell
end

class Spellcategory < ActiveRecord::Base
    belongs_to :spell, class_name: "Spell"
    belongs_to :category, class_name: "Category"
end

我已经有一个类别列表,并且想要导入一个咒语列表。 由于可以在导入过程中进行手动输入,因此我想先创建所有内容,进行显示,然后再保存所有内容(拼写+类别的链接)。 我从第一步到第二步将对象存储在activerecord-session_store中。

第一步,我从XML文件中用以下代码加载对象(有点伪代码,因为我不想让您厌倦所有XML解析):

spells = xml_doc.path(...).map do |xml_spell|
    new_spell = @user.spells.build
    xml_spell.path('cats/cat').each do |node|
       new_spell.categories << Category.find_by(name: node.text) 
    end
    new_spell
end

并保存第二步中的所有咒语。

if spells.map(&:valid?).all?
    spells.each(&:save!)
end

最后行失败,因为验证失败,并显示错误Spellcategories无效 我的猜测是它与关联表中未保存的子元素有关。 我尝试使用:autosave但没有解决问题。

我在做什么错,使我无法一劳永逸地保存一切?

如果您本身不需要访问Spellcategory模型,则可以使用has_and_belongs_to_many而不是两个has_many ,这样可以简化很多事情。

如果确实需要它,则问题的原因已在上面对该问题的注释中概述-您没有正在创建的Spell ID以能够与其保存关系。 这是我尝试的方法-两个选择:

选项1 如果您只有几条记录:

Spell.transaction do
  spells = xml_doc.path(...).map do |xml_spell|
    new_spell = @user.spells.create
    xml_spell.path('cats/cat').each do |node|
       new_spell.categories << Category.find_by(name: node.text) 
    end
    new_spell
  end
end

将其包装为事务可确保一致性。 将“ build”替换为“ create”会在添加类别之前初始化Spell记录。

选项2 如果您有很多记录。 我使用这种方法来导入数百万条记录。 保留连接表类,然后使用批量导入插件(例如https://github.com/zdennis/activerecord-import )加载数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM