2

我想知道如果有人可以幫助我的文件上傳!Ruby on Rails回形針多重上傳,嵌套屬性

我想使用回形針上傳多個圖像並具有嵌套屬性。

模式

class Trip < ActiveRecord::Base 
    has_many :trip_images, :dependent => :destroy 
end 

class TripImage < ActiveRecord::Base 
    belongs_to :trip 
    has_attached_file :photo, :styles => { :large => "800x800>", :medium => "500x500>", :thumb => "150x150#" }, :default_url => "/images/:style/missing.png" 
    validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/ 
end 

控制器

def create 
    @trip = Trip.new(trip_params) 
    respond_to do |format| 
    if @trip.save 
     format.html { redirect_to @trip, notice: 'Trip was successfully created.' } 
     format.json { render :show, status: :created, location: @trip } 
    else 
     format.html { render :new } 
     format.json { render json: @trip.errors, status: :unprocessable_entity } 
    end 
    end 
end 

def trip_params 
    params.require(:trip).permit(
    :user_id, 
    trip_images_attributes: [:id, :photo]) 
end 

視圖

<%= simple_form_for @trip, html: { multipart: true } do |f| %> 

    <%= f.simple_fields_for :trip_images do |p| %> 
    <%= p.file_field :photo, as: :file, multiple: true %> 
    <% end%> 

    <%= f.button :submit %> 

<% end %> 

我如何保存多張圖片在我的旅行圖像數據庫?當我提交表單時,沒有任何東西被保存到數據庫中。

+1

嘗試改變'trip_images_attributes:[:ID,:照片])'來'trip_images_attributes:[:ID ,:photo => []])' – Pavan

+1

並在'Trip'模型中添加'accep_nested_attributes_for:trip_images'。 – Pavan

+0

您可以發佈一條日誌,請求創建操作? –

回答

5

添加:trip_idtrip_images_attributes

def trip_params 
    params.require(:trip).permit(
    :user_id, 
    trip_images_attributes: [:trip_id, :id, :photo]) # :_destroy 
end 

你也可以添加:_destroy如果您計劃能夠刪除照片。

你還錯過了什麼是添加accepts_nested_attributes_for :trip_imagesTrip模型。

您的形式更改爲這樣的事情:

= f.simple_fields_for :trip_images do |tp| 
    = render 'trip_photos_fields', f: photo 
.links 
    %br= link_to_add_association 'Add another photo', f 

而且_trip_photos_fields.html.haml部分:

- unless f.object.new_record? 
    %br= link_to_remove_association "Delete photo", f 
    = link_to image_tag(f.object.photo.url(:medium)), f.object.photo.url, target: '_blank' 
    - if f.object.new_record? 
    = f.file_field :photo, as: :file 
+0

當我嘗試這個時,我檢查了我的數據庫,並且只有一條記錄,我嘗試檢索這條記錄,這是我得到的:'/ images/{「id 「:1,」 trip_id 「:19,」 created_at 「:」 2015-07-20T07:36:17。 820Z「,」updated_at「:」2015-07-20T07:36:17.820Z「,」photo_file_name「:null,」photo_content_type「:null,」photo_file_size「:null,」photo_updated_at「:null}'in img src tag,使用這個:'<%@ trip.trip_images.each do | img | %><%= image_tag img。to_json%><% end %>'我嘗試在這次嘗試中保存多張照片 – hellomello

+0

@hellomello,這樣你的原始問題就解決了,現在你有了另一個 - 有null而不是photo_file_name ..你有沒有安裝imagemagic?爲了回形針工作是必要的。 –

+0

好吧,它不是保存多個上傳,我試圖完成。它只保存1條記錄。另外,我通過檢查版本來檢查是否安裝了ImageMagick,我也這樣做。 '版本:ImageMagick 6.8.7-7 Q16 x86_64 2013-11-27'通過使用'convert -version' – hellomello