如何通过ActiveStorage上传视频



Active Storage 安装
$ rails active_storage:install
$ rails db:migrate



$ rails g resource video title:string introduction:text
$ rails db:migrate


/app/models/video.rb
class Video < ApplicationRecord
  has_one_attached :video
end



/app/controllers/videos_controller.rb
class VideosController < ApplicationController

  def new
    @video = Video.new
  end

  def create
    @video = Video.new(video_params)
    @video.create
    redirect_to @video
  end

  def show
    @video = Video.find(params[:id])
  end

  private

  def video_params
    params.require(:video).permit(:title, :introduction, :video)
  end
end


/app/views/videos/new.html.erb
<%= form_with model: @video, local: true do |form| %>
  <p>title</p><%= form.text_field :title %> <br>
  <p>introduction</p><%= form.text_area :introduction %> <br>
  <p>video</p><%= form.file_field :video %> <br>
  <%= form.submit %>
<% end %>



/app/views/videos/show.html.erb
<% if @video.video.attached? %>
  <p><%= @video.title %></p> <br>
  <p><%= @video.introduction %></p>
  <%= video_tag rails_blob_path(@video.video) %>
<% end %>



/app/views/videos/show.html.erb
<% if @video.video.attached? %>
  <p><%= @video.title %></p> <br>
  <p><%= @video.introduction %></p>
  <video src="<%= rails_blob_path(@video.video) %>" type="video/mp4" controls></video>
<% end %>



阅读量: 366
发布于:
修改于: