是否可以仅将嵌套表单的某些部分保存到数据库中

时间:2012-04-07 21:50:10

标签: ruby-on-rails

我有一个嵌套的形式,采取“品牌”“模型”“子模型”和“风格”...现在,任何给定的品牌+模型+子模型组合有多种风格..但我不想在我的数据库中重新保存相同的品牌名称(或模型或子模型)两次..

因此,鉴于上述情况,我需要在我的控制器中的CREATE操作中执行哪些操作,以确保数据库中的品牌名称是唯一的......等等。但是仍然可以提交嵌套表单?< / p>

此外,保存的“样式”需要采用现有子模型对象的子模型ID,如果其中一个(具有相同的子模型名称)已在子模型表中列出。

更新:

enter image description here

我想允许我的嵌套表单保存x y和z,并具有以下内容:

Panasonic(未保存,但ID已读出,并以型号x保存为brand_id) X(与Panasonic的brand_id一起保存) Y(与模型X中的model_id一起保存) Z(与Y的submodel_id一起保存)

当然,如果Model X已经存在,那么我想

松下(未保存) X(未保存) Y(以X的ID保存为model_id) Z(以Ys新ID保存为submodel_id)

你知道我要去哪里吗? =)

2 个答案:

答案 0 :(得分:0)

如果我正确地陈述你的问题,你就会有类似品牌,模型(应该将其他名字命名),子模型,风格等产品模型。我会通过创建以下模型来做到这一点:

class Brand < ActiveRecord::Base
  has_many :products
end

class Primodel < ActiveRecord::Base
  has_many :products
  has_many :submodels
end

class Submodel < ActiveRecord::Base
  has_many :products
end

class Style < ActiveRecord::Base
  has_many :products
end

class ProductsStyles < ActiveRecord::Base
  belongs_to :product
  belongs_to :style
end

class Product < ActiveRecord::Base
  belongs_to :primodel
  belongs_to :submodel
  belongs_to :brand
  has_many :products_styles
  has_many :styles, :through => :products_styles
end

这应该允许您创建和重用品牌,模型,子模型和样式。它会限制每个产品只有前三个中的一个,但允许你有多种样式。

答案 1 :(得分:0)

这就是我需要做的事情:

@brand1 = params[:brand][:name]
@model = params[:brand][:models_attributes]["0"]["name"]
@submodel = params[:brand][:models_attributes]["0"]["submodels_attributes"]["0"]["name"]
@style = params[:brand][:models_attributes]["0"]["submodels_attributes"]["0"]["styles_attributes"]["0"]["name"]

a = Brand.find_or_create_by_name(@brand1)
b = Model.find_or_create_by_name(@model, :brand_id => a.id)
c = Submodel.find_or_create_by_name(@submodel, :model_id => b.id)
d = Style.new(:name => @style, :submodel_id => c.id)
d.save