我创建了3个模型,如下所示,并使用cocoon嵌套形式在它们之间创建关联。如何在未保存的记录之间创建关联
class Unit < ApplicationRecord
has_many :mapping_categories, -> { distinct }, dependent: :destroy, inverse_of: :unit
accepts_nested_attributes_for :mapping_categories,
allow_destroy: true,
reject_if: :all_blank
end
class MappingCategory < ApplicationRecord
belongs_to :unit
has_many :mapping_items, -> { distinct }, dependent: :destroy, inverse_of: :mapping_category
accepts_nested_attributes_for :mapping_items,
allow_destroy: true
end
class MappingItem < ApplicationRecord
belongs_to :mapping_category
has_many :mapping_item_links
has_many :linked_mapping_items, through: :mapping_item_links, dependent: :destroy
end
每个mapping_item可以通过联合的表有很多其他mapping_items。在Unit窗体的每个mapping_item部分中,该关联都显示为选择输入。
创建或更新Unit时,Unit窗体中有许多mapping_categories选项卡,并且每个mapping_category部分都有很多mapping_items部分。
例如,我有映射A类和测绘类B.我想映射第1项添加到映射A类和测绘项目2到映射B类的问题是:如何创建映射项目1之间的关联和映射项目2,因为这两个项目还没有保存? 在此先感谢。
这应该搞清楚,但不要忘了申报' inverse_of'用于每个'has_many'关联,否则保存将不起作用(因为'belongs_to'在rails 5中默认是必需的,并且它不能自动推断与关联的关系)。 – nathanvda