2017-01-30 34 views
0

Rails相當新穎,並且在這裏嘗試了許多沒有成功的事情。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型號

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

我可能是誤會,但apartment_image外鍵_should_被apartment_id,因爲每個圖像屬於一個只有一間公寓,每間公寓可以有多個圖像。你能詳細說明你的問題嗎? – jjk

+0

基本上,當我點擊提交表單並檢查數據庫時,它會發布圖像或圖像,但會將其與錯誤的apartment_id關聯(即不是從表單中新創建的公寓) – Noobprogrammer

+0

爲什麼您使用'has_many雖然:'建築與公寓之間的關係?當然,公寓不能在多個建築物? – max

回答

0

所以我終於搞定了。不完全理解爲什麼這與我正在做的工作相比,但是會閱讀它(但如果它們對你們來說是顯而易見的,我也是全部耳朵)。)。

的答案是從使用其中開關/發現/ findby語句來使用Rails魔法:

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