首页 > 解决方案 > rails嵌套表单并建立多个关联

问题描述

我有property model一个has_many units。各单位has_one cost又各单位也has_one interior_amenity。加载后,new property form我想为嵌套表单构建字段,但只显示一些字段。

我想让新的属性表单app/views/properties/_form显示属于哪个单元cost的字段。interior_amenity

属性表单具有用于单位的嵌套字段。然后这些单元具有成本和内部设施的嵌套字段

我已经尝试在其中建立关联,properties_controller#new但无法同时显示成本和内部设施。

  # GET /properties/new
  def new
    @property = Property.new
    # nested fields won't initially show on the property form unless build is called here

    # chaining units and costs work but then I can't add the interior_amenity 
    @property.units.build.build_cost
    
    # the form will fail when I do this
    @property = @property.units.build
    @property.build_cost
    @property.build_interior_amenity

 
    # this causes 2 sets of unit fields to be added to the form 
    @property.units.build.build_cost
    @property.units.build.build_interior_amenity

  end

财产模型

class Property < ApplicationRecord
  has_many :units, dependent: :destroy
  accepts_nested_attributes_for :units, allow_destroy: true 
end

单元模型

class Unit < ApplicationRecord
  belongs_to :property

  has_one :cost, dependent: :destroy
  has_one :interior_amenity, dependent: :destroy

  accepts_nested_attributes_for :cost, allow_destroy: true  
  accepts_nested_attributes_for :interior_amenity, allow_destroy: true 
end

成本模型

class Cost < ApplicationRecord
  belongs_to :unit
end

室内舒适模型

class InteriorAmenity < ApplicationRecord
  belongs_to :unit
end

标签: ruby-on-rails

解决方案


推荐阅读