对Rails来说相当新,并且在这里尝试过很多东西而没有成功。
我的问题是当我使用这个嵌套表单发布到数据库时,我的一个表(apartment_images)发布了错误的外键(apartment_id)。
我有一个相当复杂的模型关系:我有一个构建 has_many_ through另一个表,它将(与其他)公寓表关联起来。有问题的 apartment_images 表属于公寓。
摘要版本如下:
建筑模型
has_many :building_relationships
has_many :apartments, :through => :building_relationships
accepts_nested_attributes_for :apartments, allow_destroy: true
公寓模型
belongs_to :building
has_many :apartment_images, -> { order(position: :asc) }, dependent: :destroy
has_many :building_relationships
has_many :buildings, :through => :building_relationships
ApartmentImage Model
belongs_to :apartment
buildings_controller(排除新方法)
def createNewBuilding
@building = Building.new(building_params)
@apartment = Apartment.where(building_id: @building.id)
#also tried this but results in no id being save:
#@apartment = @building.apartments.build(apartment_params)
if @building.save
redirect_to newBuilding_path, notice: "Successfully created building"
else
render 'newBuilding'#, notice: "ERROR"
end
if apartment_image_params
apartment_image_params[:image].each do |value|
@apartment.apartment_images.build({image: value}).save
end
end
end
def apartment_image_params
#also tried adding :apartment_id. didn't work.
params.require(:apartment_image).permit(:id, image: []) if params[:apartment_image]
end
答案 0 :(得分:0)
所以我终于开始工作了。不完全理解为什么这比我正在做的更有效,但是会对它进行阅读(但是,如果对你们这些人来说很明显,我也会全力以赴:)。
答案是从使用where / find / findby语句切换到使用Rails魔术:
def createNewBuilding
@building = Building.new(building_params)
@apartments = @building.apartments
@apartments.each do |apartments|