Rails 嵌套表单创建了错误的外键

Rails Nested Form Creating Wrong Foreign Key

Rails 还很陌生,在这里尝试了很多东西都没有成功。

我的问题是当我 post 使用这种嵌套形式访问数据库时,我的 tables (apartment_images) posts 之一的外键错误(apartment_id).

我有一个相当复杂的模型关系:我有一个 Building has_many_through 另一个 table 将它与(除其他外)关联 公寓table。有问题的apartment_imagestable属于Apartments.

摘要版本如下:

建筑模型

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

公寓形象模型

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

所以我终于让它工作了。不完全理解为什么这与我所做的相比有效,但会继续阅读它(但如果你们很明显,我也会洗耳恭听 :))。

答案是从使用 where / find / findby 语句切换到使用 Rails 魔法:

def createNewBuilding
@building = Building.new(building_params)
@apartments = @building.apartments
@apartments.each do |apartments|