我正在构建一个表单,用户应该可以使用字段创建模板.不过,他们也应该能够创建可选Collection其中belongs_to每个Field在同一时间.
到目前为止它看起来像这样:
表
templates: id, name
template_fields: id, template_id, collection_id, field_name
collections: id, name
collection_values: id, collection_id, value
Run Code Online (Sandbox Code Playgroud)
楷模
模板
class Template < ActiveRecord::Base
has_many :template_fields
accepts_nested_attributes_for :template_fields
end
Run Code Online (Sandbox Code Playgroud)
模板字段
class TemplateField < ActiveRecord::Base
belongs_to :template
belongs_to :collection
end
Run Code Online (Sandbox Code Playgroud)
采集
class Collection < ActiveRecord::Base
has_many :collection_values
end
Run Code Online (Sandbox Code Playgroud)
CollectionValue
class CollectionValue < ActiveRecord::Base
belongs_to :collection
end
Run Code Online (Sandbox Code Playgroud)
我该如何创建这些对象?我如何在控制器中进行此操作?
我能想到的唯一方法是将其创建为嵌套关联(即使Collection不是真正的嵌套属性),也可以在模板之前创建集合,并以某种方式将每个Field链接到创建的每个Collection.
调节器
def create
@template = Template.new(template_params)
if @template.save
flash[:notice] = "Template successfully created."
flash[:color]= "valid"
redirect_to templates_path …Run Code Online (Sandbox Code Playgroud)