6.0 來(lái)引入Active Stora..."/>
您好,登錄后才能下訂單哦!
在Rails中實(shí)現(xiàn)文件上傳可以通過(guò)使用內(nèi)置的Active Storage功能來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的步驟:
首先,在Gemfile中添加gem 'rails', '~> 6.0'
來(lái)引入Active Storage功能。
然后在終端中運(yùn)行bundle install
安裝Gem。
運(yùn)行rails active_storage:install
來(lái)生成Active Storage的配置文件。
在model中使用has_one_attached
或has_many_attached
宏來(lái)指定有關(guān)文件上傳的字段。
class User < ApplicationRecord
has_one_attached :avatar
end
<%= form_with(model: @user, local: true) do |form| %>
<div class="field">
<%= form.label :avatar %>
<%= form.file_field :avatar %>
</div>
<%= form.submit %>
<% end %>
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:avatar)
end
end
<%= image_tag @user.avatar if @user.avatar.attached? %>
這樣就實(shí)現(xiàn)了文件上傳的功能。更多關(guān)于Active Storage的使用可以查看官方文檔:https://edgeguides.rubyonrails.org/active_storage_overview.html.
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。