我对Ruby On Rails
完全陌生。我试图创建一个可以将文件上传到本地存储的应用程序。我正在使用ActiveStorage
。执行完所有步骤后,我无法上传文件。我正在分享可能需要帮助的代码。
- new.html.ebr
<h1>Add New Post</h1>
<%= form_for @test do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
</p>
<p>
<%= f.label :file %><br>
<%= f.file_field :file %><br>
</p>
<p>
<%= f.submit "Add Post" %><br>
</p>
<% end %>
- test_controller.rb
class TestsController < ApplicationController
def index
end
def new
@test = Test.new
end
def create
@test = Test.new(test_params)
if @test.save
redirect_to tests_path
else
redirect_to "new"
end
end
def test_params
params.require(:test).permit(:title, :file)
end
end
- test.rb
class Test < ApplicationRecord
has_one_attached :file
end
- 模型迁移代码(以防万一)
class CreateTests < ActiveRecord::Migration[5.1]
def change
create_table :tests do |t|
t.string :title
t.string :file
t.timestamps
end
end
end
提交表单后,仅tests
表被更新。 file
列中的值为#<ActionDispatch::Http::UploadedFile:0x000000000d5bec50>
,而不是文件路径。并且需要更新的表active_storage_attachments and active_storage_blobs
不会更新。
编辑:我正在添加日志以获取更多信息
于2019-05-31 12:25:25 +0530开始为127.0.0.1进行POST“ /测试” 由TestsController#create处理为HTML
参数:{“ utf8” =>“✓”, “ authenticity_token” =>“ W9EE8ot + SzsJQMzgQ6gVWqER2TIXN2mUW7PBgTt0DV8mskeR2oGO / iHTx + quBT0cXTLobU60SoFsceNOzA8 + 2Q ==”, “ test” => {“ title” =>“ sss”,“ file” =>#'<'ActionDispatch :: Http: :UploadedFile:0x000000000d0a25c8> @ tempfile =#, @ original_filename =“ contacts.vcf”,@ content_type =“ text / x-vcard”,@head ers =“ Content-Disposition:form-data; name = \” test [file] \“; filename = \“ contacts.vcf \” \ r \ n内容类型:text / x-vcard \ r \ n“>}, “ commit” =>“添加帖子”}
(0.1ms)开始
SQL(0.8ms)插入“测试”(“标题”,“文件”,“ created_at”, “ updated_at”)值($ 1,$ 2,$ 3,$ 4)返回“ id” [[“ title”, “ sss”],[“文件”,“#”],[“ created_at”,“ 2019-05-31 06:55:25.837658”], [“ updated_at”,“ 2019-05-31 06:55:25.837658”]]
(26.6ms)COMMIT
重定向到http://localhost:3000/tests
在34毫秒内完成302发现(ActiveRecord:27.5毫秒)
**任何人都可以说此问题是否是由于Rails版本引起的吗?
谢谢。