我是ruby的新手,我会感激任何帮助。我在ruby中创建了一个文件上传器。当我单独测试时,它工作得很好!但是当我把它渲染成另一种形式时,它就不起作用了!这是我的代码:
上传/ _index.html.erb
<h4>Upload File </h4>
<%= form_tag({:controller => 'upload', :action => 'upload_image'}, :multipart => true, remote: true) do %>
<p><label for="upload_file">Select file..</label>
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload", :class => "btn btn-default btn-lg active", :method => 'post' %>
<% end %>
data_file.rb
class DataFile < ActiveRecord::Base
attr_accessor :upload
belongs_to :event
def self.save_file(upload)
file_name = upload['datafile'].original_filename if (upload['datafile'] !='')
file = upload['datafile'].read
file_type = file_name.split('.').last
new_name_file = Time.now.to_i
name_folder = new_name_file
new_file_name_with_type = "#{new_name_file}." + file_type
directory = 'public/data'
Dir.mkdir(directory + "#{name_folder}");
File.open(directory + "#{name_folder}/" + new_file_name_with_type, "wb") do |f|
f.write(file)
end
end
end
upload_controller.rb
class UploadController < ApplicationController
before_filter :authenticate_user!
before_filter do
redirect_to :root unless current_user && current_user.isAdmin?
end
def index
# @users = User.find(params[:id])
redirect_to new_event_path
end
def upload_image
DataFile.save_file(params[:upload])
#redirect_to new_event_path
end
end
我已将上传/索引呈现到events / new.html.erb
<div style="margin-left: 360px;"><h1>New event</h1></div>
<br/>
<br/>
<div style="margin-left: 360px;">
<%= form_for(:event, :url => {:controller => 'events', :action => 'new'}, html: { method: :post }) do |f| %>
<% if @event.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@event.errors.count, "error") %> prohibited this event from being saved:</h2>
<ul>
<% @event.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :event_Day %><br>
<select name="event_day_id">
<option value="0">-Choose agenda item-</option>
<% for agenda_item in @agenda_items %>
<option value="<%= agenda_item.id %>"><%= agenda_item.name %></option>
<% end %>
</select>
</div>
<%= link_to 'Add new agenda item', new_agenda_item_path %>
<br/>
<br/>
<div class="field">
**<%= render :partial => 'upload/index' %>**
</div>
<br/>
<div class="field">
<div class="field">
<%= f.label :Survey %><br>
<select name="survey_id">
<option value="0">-Choose survey-</option>
<% for survey in @surveys %>
<option value="<%= survey.id %>"><%= survey.title %></option>
<% end %>
</select>
</div>
<%= link_to 'Create new survey', new_survey_path %>
</div>
<div class="actions">
<%= f.submit :class => "btn btn-default btn-lg active", :method => 'post' %>
</div>
<% end %>
</div>
<%= button_to 'Back', events_path, :class => 'btn btn-primary btn-lg active', :method => 'get' %>
谢谢!
答案 0 :(得分:0)
抱歉,我刚注意到这个问题不完整。我已回答了这个问题。将上载文件表单呈现为另一种形式时,它不起作用。所以我将它从表单中删除并将其放在顶部,一切正常。
除非有办法将一个形式嵌套在另一个中吗?
谢谢!