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