我坚持上传文件。我正在使用复杂的表格。这是一个模型:
class Project < ActiveRecord::Base
has_one :task
accepts_nested_attributes_for :task
end
class Task < ActiveRecord::Base
has_one :project
accepts_nested_attributes_for :project
end
这是一个视图:
<%= form_for(@project) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<%= f.fields_for :task_attributes do |a| %>
<div class="field">
<%= a.label :name %><br />
<%= a.text_field :name %>
<%= form_tag 'project/upload', :multipart => true do %>
<label for="file">Upload text File</label><%= a.file_field :path %>
<% end %>
</div>
<% end %>
<% end %>
这是一个控制器:
class ProjectsController < ApplicationController
def new
@project = Project.new
@project.build_task
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @project }
end
end
def upload
uploaded_io = params[:upload][:path]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
file.write(uploaded_io.read)
end
end
def create
@project = Project.new(params[:project])
respond_to do |format|
if @project.save
format.html { redirect_to(@project, :notice => 'Project was successfully created.') }
format.xml { render :xml => @project, :status => :created, :location => @project }
else
format.html { render :action => "new" }
format.xml { render :xml => @project.errors, :status => :unprocessable_entity }
end
end
end
end
移民:
class CreateProjects < ActiveRecord::Migration
def self.up
create_table :projects do |t|
t.integer :id
t.string :name
t.timestamps
end
end
def self.down
drop_table :projects
end
end
class CreateTasks < ActiveRecord::Migration
def self.up
create_table :tasks do |t|
t.string :name
t.integer :project_id
t.string :path
t.timestamps
end
end
def self.down
drop_table :tasks
end
end
当我通过表单创建带有任务的新项目时,我在数据库中有两条记录。我在数据库中看到任务文件路径。但是我在我的公共目录中看不到文件。我不知道如何将文件保存到公共目录。
请帮我解决这个问题!