0

屬性具有多個圖片。在表單中上傳的圖像應該可以通過Property類訪問。提交表格時接​​收如何通過回形針在rails 5中的fields_for表單中將參數傳遞給嵌套屬性

//Picture Model 
class Picture < ApplicationRecord 
    belongs_to :property 
    has_attached_file :image, styles: { medium: "300x300>", thumb:"100x100>" }, default_url: "/images/:style/missing.png" 
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ 
end 

//Property Model 
class Property < ApplicationRecord 
    has_many :pictures, dependent: :destroy 
    accepts_nested_attributes_for :pictures 
end 

//Form 
<%= form_for @property, :html => {multipart: true} do |f| %> 
    <%= f.fields_for :pictures do |ph| %> 
    <%= ph.file_field :image, as: :file %> 
    <% end%> 
<% end%> 

//Properties Controller 
def new 
    @property = Property.new 
    @property.pictures.build 
end 

def create 
    @property = current_user.properties.build(property_params) 
    @property.seller = User.find(current_user.id) # links user to property via. user_id 
    respond_to do |format| 
    if @property.save 
     format.html { redirect_to @property, notice: 'Property was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @property } 
    else 
     format.html { render action: 'new' } 
     format.json { render json: @property.errors, status: :unprocessable_entity } 
    end 
    end 
end 

錯誤:圖片屬性必須存在

回答

0

在導軌5,belongs_to的存在爲自動驗證。您可以添加optional: true到belongs_to的:

class Picture < ApplicationRecord 
    belongs_to :property, optional: true 
end 

或者你有你創建圖片之前保存物業:

編輯:簡單的方法來保存屬性之前創建的圖片

# PropertyController 
def create 
    @property = current_user.properties.build(property_params) 
    @property.seller = User.find(current_user.id) # links user to property via. user_id 
    respond_to do |format| 
    if @property.save 
     @property.picture.create(picture_params) 
     format.html { redirect_to @property, notice: 'Property was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @property } 
    else 
     format.html { render action: 'new' } 
     format.json { render json: @property.errors, status: :unprocessable_entity } 
    end 
    end 
end 

def picture_params 
    params.require(:property).permit(:picture) 
end 
+0

權,如果我這樣做然後他們不鏈接。我將如何在圖片之前保存該屬性? – Supplicant

+0

請參閱圖片中使用'belongs_to:property'時,意味着您將保存property_id em圖片,因此必須先保存屬性!一個簡單的方法是:在@ property.save後你可以執行@ property.pictures.create(picture_params)' –

+0

我編輯了我的答案,把我的建議放在上面 –

相關問題