[Rails] Voice posting function ~ Cloudinary, CarrierWave

Introduction

In this article, we will implement the audio file posting function.

Use Cloudinary (external storage). You can use up to 1GB per month with a free plan.

Premise

In the Tweet model, the text posting function is complete.

First, ...

Register for an account on Cloudinary! Don't forget to register with your e-mail address!

https://cloudinary.com/

After getting the above account, please start the following work!

Add audio column

Add an audio column of type string to the tweets table.

Terminal


$ rails generate migration AddAudioToTweets audio:string

Terminal


$ rails db:migrate

The URL (address) of the audio file is written in this audio column. The audio file itself is saved in a different location.

Index.html.erb

Write the code to play the audio file

erb:app/views/tweets/index.html.erb


    <% @tweets.each do |t| %>

        <%= audio_tag t.audio_url, :controls => true if t.audio? %>

    <% end %>

controls =>true displays the controller panel.


 In addition, audio_tag has the following options.

 ``: autoplay`` Autoplay
 ``: loop`` Loop playback

### Strong parameters

 Describe it in the strong parameter so that it can receive the audio parameter.


#### **`tweets_controller.rb`**
```ruby

#Omitted

private
def tweet_params
  params.require(:tweet).permit(:body, :audio)
end

new.html.erb

Write the code to upload the file.

erb:app/views/tweets/new.html.erb



<%= form_for @tweet do |f| %>

  <div class="field">
    <%= f.label :audio %>
    <%= f.file_field :audio %>
  </div>

  <%= f.submit "Tweet" %>
<% end %>

Add gem

This time we will use cloudinary and a gem called carrierwave. Add the following to the bottom of your Gemfile:

Gemfile


gem 'carrierwave'
gem 'cloudinary'

Terminal


$ bundle install

carrierwave cloudinary

To briefly explain each gem carrierwave: A gem that allows you to upload files with rails cloudinary: A gem to make cloudinary, an external storage service, available

Creating an uploader

Create an uploader with the CarrierWave generator. Type the following command into your terminal.

Terminal


$ rails g uploader Audio

Model modification

Modify app / models / tweet.rb as follows.

app/models/tweet.rb


class Tweet < ApplicationRecord

#Postscript from here
  mount_uploader :audio, AudioUploader
#Postscript up to here

end

audio,Audio Uploader means to save the audio file to the specified location.



 Next is the uploader settings that specify the save location.

 Let's change the 6th to 8th lines of app / uploaders / image_uploader.rb.


#### **`app/uploaders/audio_uploader.rb`**
```ruby

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

Change the above as shown in the figure below.

app/uploader/audio_uploader.rb


  # Choose what kind of storage to use for this uploader:
  if Rails.env.production?
    include Cloudinary::CarrierWave
    CarrierWave.configure do |config|
      config.cache_storage = :file
    end
  else
    storage :file
  end
  # storage :fog

cloudinary is an external storage service. In the production environment (after release = production), the image is saved in the cloudinary, and in other cases (development environment = local), it is saved in your pc. (Saved in public folder)

Private API key

Each Cloudinary account is given a "Cloud name", "API Key", and "API Secret".

Cloudinary My Page

Cloudinary_Management_Console_-_Dashboard_png.png

Increase security to prevent your Cloudinary account from being leaked to the outside world.

Here, we will use a gem called dotenv-rails. Add the following to the bottom of your Gemfile:

Gemfile


gem 'dotenv-rails'

Terminal


$ bundle install

To install.

Then create a file called .env yourself in the ** application directory (the directory where the app, db and gemfiles are located) **. If it looks like the figure below, it's okay.

スクリーンショット_2018-10-17_2_03_28.png

Then enter the following in the .env file you created.

.env


CLOUD_NAME=q0w9e8r7t6yu5  #← This value varies from person to person! !!
CLOUDINARY_API_KEY=123456789012345 #← This value varies from person to person! !!
CLOUDINARY_API_SECRET=1a2s3d4f5g6h7j8k9l0a1s2d4f5g6h1q #← This value varies from person to person! !!

Here, rewrite each value after "=" with the key obtained in Cloudinary My Page earlier (the key you obtained is absolutely other). Don't say it !! Also, the numbers vary from person to person). Also, when rewriting, ** delete the commented out part **!

Finally, don't publish the .env file that defines the data you want to hide.

Add the following to .gitignore. ** * If the .gitignore file does not exist, create it in the application directory! ** </ font>

.gitignore


#abridgement

/.env

This is OK!

Use of API key

This is the final step! First, create a cloudinary.yml file in your config folder.

スクリーンショット_2019_10_20_1_11.png

Just copy and paste it into config / cloudinary.yml as below.

config/cloudinary.yml



development:
  cloud_name: <%= ENV['CLOUD_NAME'] %>
  api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
  api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
  enhance_image_tag: true
  static_file_support: false
production:
  cloud_name: <%= ENV['CLOUD_NAME'] %>
  api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
  api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
  enhance_image_tag: true
  static_file_support: false
test:
  cloud_name: <%= ENV['CLOUD_NAME'] %>
  api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
  api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
  enhance_image_tag: true
  static_file_support: false

You can now use the API key while keeping it private.

You can now post audio files. thank you for your hard work(^^)/

Official documentation

carrierwave cloudinary dotenv-rails

Recommended Posts

[Rails] Voice posting function ~ Cloudinary, CarrierWave
[Rails] Implement image posting function
Add pdf file posting function with carrierwave
[Rails] Image posting by CarrierWave [AWS EC2]
Multiple image upload function using Rails Carrierwave
[Rails 6] Ranking function
Image posting function
[Rails] Introduce Carrierwave
[Rails] Category function
Rails follow function
[Rails] Notification function
Posting function implemented by asynchronous communication in Rails
Upload multiple images easily with rails rails + carrierwave + cloudinary
[Ruby on Rails] Asynchronous communication of posting function, ajax
[Rails] Implement search function
[Rails] Implemented hashtag function
[Ruby on Rails] Posting score ranking function (whole display)
[rails] tag ranking function
Rails search function implementation
Implement application function in Rails
Search function using [rails] ransack
Implement follow function in Rails
[Rails] Save images using carrierwave
[Rails 6] Implementation of search function
[Rails] Implementation of category function
Rails ~ Understanding the message function ~
[Rails] (Supplement) Implemented follow function
Login function implementation with rails
[Rails] EC site cart function
Ajax bookmark function using Rails
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
[Rails 6] Pagination function implementation (kaminari)
[Ruby on Rails] Posting function that only logged-in users can post