我在我的rails应用程序中使用paperclip
我的表格是
<%= 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 %>
和控制器操作是
def portfolio_photo_uplaod
@portfolio_photo = IndividualPhoto.create(portfolio_photo_params)
if @portfolio_photo.save
redirect_to individual_profile_path(current_individual)
end
end
且强参数
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
我可以保存当我上传单张图片但我无法保存多张图片而只是当我上传多张图片时,只有一张图片保存在数据库中 请帮忙!!
答案 0 :(得分:1)
以下是您当前系统的答案:
以您的形式:
<%= 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 %>
在您的控制器中:
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
和强参数:
def portfolio_photo_params
params.permit(:profile_id, :portfolio_photos => [])
end
根据您当前的设计,上述解决方案应该可行,但它还不是最佳方法,您可以采用更好的方法来实现这一目标,例如:使用accepts_nested_attributes_for
通过配置文件控制器更新配置文件的照片。