ruby-on-rails - 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
解决方案
推荐阅读
- javascript - 使用应用引擎服务部署时出现 502 bad gateway
- reactjs - 数据映射问题 - 无法读取未定义的属性“文档”
- c - 可变长度位域
- arrays - 如何在不添加新行的情况下在 WordPress 帖子内容中添加空间
- node.js - AWS Serverless 403 禁止 API 网关
- php - readFile 和 file_get_contents 呈现损坏的 PDF 和 PNG 文件,但 JPG 很好
- javascript - 避免在带有 Mocha 测试的 Elasticsearch 请求中使用 setTimeout()
- c# - 从获取请求中获取 null 但上下文返回值
- python - Gunicorn 重新加载未检测到应用程序代码中的更改
- r - 预测 lme4 中的值