2017-04-05 25 views
0

我看到了類似的回答問題here,這讓我感到目前爲止。但現在我在Form中面臨一個錯誤。我正在尋找的解決方案基本上保存到Ruby Rails中的兩個表中,其中在第一個表中保存屬性與地址也在圖片的第二個表中保存了2個圖像。在Ruby Rails中保存到2個表格時出現錯誤

Migration1:

class CreateProperties < ActiveRecord::Migration[5.0] 
    def change 
    create_table :properties do |t| 
     t.string :address 

     t.timestamps 
    end 
    end 
end 

Migration2:

class CreatePictures < ActiveRecord::Migration[5.0] 
    def change 
    create_table :pictures do |t| 
     t.string :image1 
     t.string :image2 

     t.timestamps 
    end 
    end 
end 

物業型號:

class Property < ApplicationRecord 
    has_many :pictures 
    accepts_nested_attributes_for :pictures 
end 

圖片型號:

class Picture < ApplicationRecord 
    belongs_to :property 
end 

PropertiesController:

class PropertiesController < ApplicationController 
before_action :set_property 

    def new 
    @property = Property.new 
    end 

    def create 
    @property = properties.build(property_params) 
    if @property.save 
     flash[:success] = "Property was successfully created" 
     redirect_to property_path(@property) 
    else 
     render 'new' 
    end 
    end 

    private 
    def property_params 
     params.require(:property).permit(:address, picture_attributes: [:image1, :image2]) 
    end 
end 

,我不知道是按以下步驟進行形式:

<%= form_for(@property) do |f| %> 
<%= f.label :address %> 
<%= f.text_field :address %> 

<%= f.label :image1 %> 
<%= f.text_field :image1 %> 

<%= f.label :image2 %> 
<%= f.text_field :image2 %> 
<%= f.submit %> 
<% end %> 

錯誤圖片:

Error on new.html.erb

+0

有時候,表單對象是建立複雜嵌套關係的複雜嵌套表單的一個很好的選擇。只需搜索「軌道上的紅寶石形式的對象」以獲取更多信息... –

+0

感謝Brad的技巧,請在此明確地閱讀! – TheMissingNTLDR

回答

2

您應該使用fields_for方法有一張表格內的圖片:

# inside the property form_for 
<%= f.fields_for @property.pictures.build do |p| %> 
    <%= p.file_field :image1 %> 
    <%= p.file_field :image2 %> 
<% end %> 
+0

謝謝Amr!明天一定會嘗試這個,並會回報。 – TheMissingNTLDR

+0

最後一件事,在你的'property_params'裏是'pictures_attributes'而不是'picture_attributes'。希望這可以幫助! – amrrbakry

+0

是的,我正在用單數/複數玩弄,但現在堅持複數! – TheMissingNTLDR

相關問題