6.0 來(lái)引入Active Stora..."/>
溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Rails中實(shí)現(xiàn)文件上傳

發(fā)布時(shí)間:2024-06-05 17:34:06 來(lái)源:億速云 閱讀:88 作者:小樊 欄目:web開(kāi)發(fā)

在Rails中實(shí)現(xiàn)文件上傳可以通過(guò)使用內(nèi)置的Active Storage功能來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的步驟:

  1. 首先,在Gemfile中添加gem 'rails', '~> 6.0'來(lái)引入Active Storage功能。

  2. 然后在終端中運(yùn)行bundle install安裝Gem。

  3. 運(yùn)行rails active_storage:install來(lái)生成Active Storage的配置文件。

  4. 在model中使用has_one_attachedhas_many_attached宏來(lái)指定有關(guān)文件上傳的字段。

class User < ApplicationRecord
  has_one_attached :avatar
end
  1. 在表單中添加文件上傳字段。
<%= form_with(model: @user, local: true) do |form| %>
  <div class="field">
    <%= form.label :avatar %>
    <%= form.file_field :avatar %>
  </div>
  <%= form.submit %>
<% end %>
  1. 在controller中處理文件上傳。
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
  1. 最后,在視圖中顯示上傳的文件。
<%= image_tag @user.avatar if @user.avatar.attached? %>

這樣就實(shí)現(xiàn)了文件上傳的功能。更多關(guān)于Active Storage的使用可以查看官方文檔:https://edgeguides.rubyonrails.org/active_storage_overview.html.

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI