简体   繁体   中英

rails 4 paperclip not uploading multiple images but just one

I am using paperclip in my rails app

my form is

<%= form_for @portfolio_photo, :url => portfolio_photo_uplaod_individual_profile_path(:profile_id => current_individual.profile.id), :method => :POST, :html => { :multipart => true } do |f| %>
  <%= f.hidden_field :profile_id, :value => current_individual.profile.id %>
  <%= file_field_tag :portfolio_photo, multiple: true %>
  <%= f.submit "submit" %>
<% end %>

and controller action is

def portfolio_photo_uplaod
  @portfolio_photo = IndividualPhoto.create(portfolio_photo_params)
  if @portfolio_photo.save
    redirect_to individual_profile_path(current_individual)
  end
end

and the strong parameters are

def portfolio_photo_params
  params.permit(:portfolio_photo, :profile_id)
end

individual_photo.rb

class IndividualPhoto < ActiveRecord::Base
  belongs_to :profile

  has_attached_file :portfolio_photo, :styles => { :medium => "300x300>" }
  validates_attachment_content_type :portfolio_photo, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end

profile.rb

has_many :individual_photos

i am able to save when i upload a single image but i am not able to save multiple images instead only one image is saving in the database when i upload multiple images Please help !!

Here is the answer for your current system:

In your form:

<%= form_for @portfolio_photo, :url => portfolio_photo_uplaod_individual_profile_path(:profile_id => current_individual.profile.id), :method => :POST, :html => { :multipart => true } do |f| %>
  <%= f.hidden_field :profile_id, :value => current_individual.profile.id %>
  <%= file_field_tag 'portfolio_photos[]', multiple: true %>
  <%= f.submit "submit" %>
<% end %>

In your controller:

def portfolio_photo_uplaod
  portfolio_photo_params[:portfolio_photos].each do |photo|
    IndividualPhoto.create(portfolio_photo: photo, profile_id: portfolio_photo_params[:profile_id])
  end
  redirect_to individual_profile_path(current_individual)
end

and the strong parameters:

def portfolio_photo_params
  params.permit(:profile_id, :portfolio_photos => [])
end

With your current design, above solution should work but it's not the best approach yet, you have some better ways to achieve this eg using accepts_nested_attributes_for to update Profile's photos through Profile Controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM