如何使用 Rails 获取从表单上传的文件以显示到另一个视图?



>新手到Rails在这里。所以我正在为我的项目创建一个在线图书馆,在那里我可以上传用户选择的电子书(以 pdf 的形式(。表格,添加漫画接受两个文件:缩略图(jpg,jpeg,png(和电子书的实际pdf。

我想知道如何从表单中获取缩略图和 pdf 文件,并将其显示在我的显示视图中。

谢谢!

1(我尝试在标签标签中引入img标签,但是使用当前脚本,什么也没返回。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<%= csrf_meta_tag %>
<title>Document</title>
</head>
<body>
<div class="container">
<div class="information">
<h1>Title</h1>
<p><%= @book.title%></p>
<h1>Author</h1>
<p><%= @book.author%></p>
<h1>Description</h1>
<p><%= @book.description%></p>
</div>
</div>
<%= link_to "Edit", edit_book_path(@book), :class => "btn btn-default" %>
<!--after you make this make edit method in books controller-->
<%= button_to "Delete", book_path(@book),
method: :delete,
data: {confirm: 'Are you sure?'},
:class => "btn btn-danger" %>
</body>
</html>
This is my books controller. 
class BooksController < ApplicationController
skip_before_action :verify_authenticity_token
def index  #step 4
@books = Book.all
end
def show #step 3
@book = Book.find(params[:id]) #get individual post page
end
def newBook 
@book = Book.new
#creates a new post of registered books 
end
def create #Step 2
#render plain: params[:books].inspect #see what data is sent
@book = Book.new(book_params)
if(@book.save)
redirect_to @book
else
render 'newBook' #if title is not there, just re renders newBook page
end
end
def edit 
@book = Book.find(params[:id]) #after this, make edit.html.erb
end
def update
@book = Book.find(params[:id]) 
if(@book.update(book_params))
redirect_to @book
else
render 'edit'
end
end
def destroy 
@book = Book.find(params[:id])
@book.destroy
redirect_to books_path
end
def mangaList
@books = Book.all
end
private 
def book_params #can only be accessed from this class #step1 
params.require(:books).permit(:title, :author, :description)
end
end

我尝试在book_params中添加一个 :file,但它不起作用。

Rails 提供了一种通过ActiveStorage上传文件的简单方法(也很少有 gem 可以做同样的事情,但现在你可以尝试ActiveStorage因为它是内置的解决方案(。

官方指南是开始深入研究此主题的良好资源。您可以在此处找到ActiveStorage相关文章:

https://guides.rubyonrails.org/active_storage_overview.html

还有很多关于如何在互联网上设置它的教程。如果你更喜欢视频人GoRails提供了很好的概述:

https://gorails.com/episodes/file-uploading-with-activestorage-rails-5-2?autoplay=1

基本上,您需要向应用程序添加一些配置,并将相关字段添加到模型中。在此之后,您将能够将参数中的文件传递给控制器并将其表示形式保存在数据库中。这将允许您在视图中从实例变量中检索它们(就像您现在使用titleauthordescription一样。

希望这有帮助!

文件是属性还是关联? 您尝试在哪个模型中上传文件是书籍还是其他关联模型?

最新更新