我是Stackoverflow的新手,正在学习Ruby on Rails,使用Carrierwave进行图片上传。我正在创建一个通讯录,并在一次更新多个图像时遇到问题。在新的联系表单中,我设置了它,以便用户可以添加多个逗号分隔的联系人和一个复选框(如果用户想要添加图像)。我遇到的问题是当用户有多个新联系人并想要添加图像时图像没有上传,其他情况都正常。这是我的控制器,非常感谢任何帮助。
class ContactsController < ApplicationController
before_action :require_user
before_action :set_contact, only: [:show, :edit, :destroy, :update]
def new
@contact = Contact.new
end
def create
@group = Group.find(session[:group_id])
@contacts = []
redirect_path = nil
render_path = nil
if ",".in? contact_params[:name]
#create multiple contact objects in @contacts array
@strings = contact_params[:name].split(/,/)
@strings.count.times do
@contacts << Contact.new
end
@contacts.each_with_index do |contact, index|
contact.name = @strings[index].strip
contact.user = current_user
contact.group_id = @group.id
if contact.save
flash[:success] = "Saved"
redirect_path = group_path(@group)
else
flash[:danger] = "Failed to save"
redirect_path = edit_multiple_contacts_path(@contacts)
end
end
if params[:cbox] == "true"
#need to go to edit multiple
redirect_path = nil
render_path = 'edit_multiple'
else
#do nothing
end
else
@contact = Contact.new(contact_params)
@contact.user = current_user
@contact.group_id = @group.id
if @contact.save
#flash[:success] = "Saved"
redirect_path = group_path(@group)
else
flash[:danger] = "Failed to save"
end
if params[:cbox] == "true"
redirect_path = edit_contact_path(@contact)
else
#do nothing
end
end
if redirect_path.nil?
render render_path
else
redirect_to(redirect_path)
end
end # end of create
def show
end
def edit
end
def destroy
@group = Group.find(session[:group_id])
@contact.destroy
flash[:success] = "This contact has been removed"
redirect_to group_path(@group)
end
def update
@group = Group.find(session[:group_id])
if @contact.update(contact_params)
flash[:success] = "#{@contact.name} has been updated"
redirect_to group_path(@group)
else
render 'edit'
end
end
def edit_multiple
end
def update_multiple
@group = Group.find(session[:group_id])
@contacts = Contact.update(params[:contacts].keys, params[:contacts].values)
@contacts.reject! { |u| u.errors.empty? }
if @contacts.empty?
redirect_to group_path(@group)
else
render 'edit_multiple'
end
end #end update_multiple
private
def set_contact
@contact = Contact.find(params[:id])
end
def contact_params
params.require(:contact).permit(:name, :image, :contacts)
end
end