该应用程序的目标是方便用户上传/下载文件。
如果用户未选择任何文件并尝试点击上传,则需要显示提示。
def create
@user = User.find(params[:user_id])
@attachment = Attachment.new(params[:attachment => {:file => [ :original_filename ]}])
if params[:attachment].nil?
flash[:alert] = "No file!"
render "new"
end
uploaded_io = params[:attachment][:file]
@attachment.user_id = @user.id
@attachment.name = params[:attachment][:file].original_filename
@attachment.format = params[:attachment][:file].content_type
@attachment.save
File.open(Rails.root.join('public/data', @attachment.name), 'wb') do |file|
file.write(uploaded_io.read)
end
redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been uploaded."
end
尽管有if params[:atttachment].nil?
阻止,但我在uploaded_io = params[:attachment][:file]
语句中收到错误。
params[:attachment].nil?
会返回true
[使用调试器检查]
if块未执行的原因是什么?
答案 0 :(得分:1)
你只有一个if循环,所以不管代码是否进入if循环,你都在执行if循环之外的每个代码,如果是else你需要处理它。这意味着代码之后如果循环将始终执行,如果它依赖于params[:attachment]
则不应该这样
我已使用正确的if else循环..更新了您的代码...
def create
@user = User.find(params[:user_id])
@attachment = Attachment.new(params[:attachment => {:file => [ :original_filename ]}])
##you can use .blank? as well
if params[:attachment].nil?
flash[:alert] = "No file!"
render "new"
else
uploaded_io = params[:attachment][:file]
@attachment.user_id = @user.id
@attachment.name = params[:attachment][:file].original_filename
@attachment.format = params[:attachment][:file].content_type
@attachment.save
File.open(Rails.root.join('public/data', @attachment.name), 'wb') do |file|
file.write(uploaded_io.read)
end
redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been uploaded."
end
end
答案 1 :(得分:1)
你需要返回才能渲染,否则你会得到双重渲染错误,试试这样的事情
if params[:attachment].nil?
flash[:alert] = "No file!"
return render "new"
end
另外另一个注意事项是,当你直接渲染时,flash消息不会出现,它出现在下面的请求中,而是你需要告诉rails你希望那个flash消息立刻出现,所以不要只是使用flash
,使用flash.now
if params[:attachment].nil?
flash.now[:alert] = "No file!"
return render "new"
end