LoginSignup
0
0

More than 3 years have passed since last update.

Active Strageでファイル形式を指定して保存

Last updated at Posted at 2021-02-25

今回はrailsでの動画投稿機能実装のアウトプットです。

動画投稿の際にActive Strageでmp4ファイルのみ保存させたかったので、自己流ではありますが今回はcontroller側で制御する形で実装しました。

posts_controller.rb
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.valid? && @post.video.content_type == "video/mp4"
      @post.save
      redirect_to posts_path
    else
      render :new
    end
  end

  private
  def post_params
    params.require(:post).permit(:title, :video).merge(user_id: current_user.id)
  end
end
models/post.rb
class Post < ApplicationRecord
  belongs_to :user
  has_one_attached :video

  validates :title, :video, presence: true
end

今回はcontent_typeで保存するデータのファイル形式を指定できるということに気づくことが出来ました。
ですが本当は他の書き方で、より効率的に、ファイルサイズ等もまとめて指定して書ける方法があるのだと思います。
モデル側で書く方が正しいのかもしれません。

まだまだ自分は初心者なので、
よりDRYな実装ができるよう更に学習を深めて改善に努めていきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0