20200624のRailsに関する記事は14件です。

flag_icon_cssを使って、railsに国旗を表示させる

fontawesomeに国旗がないぞorz

fontawesomeで、国旗のフォントを探してみると....

ない...ないのか...

他に使えそうなものないかなと調べてみると、
flag_icon_css_railsなるものが!!

使い方は、README.mdにあるとおりですが、一応記録に残しておきます。

①'flag_icon_css_rails'のインストール

gemfile
gem 'flag_icon_css_rails'
bundle install
rails g flag_icon_css_rails

②requireします

application.scss@import 'flag-icon';を追記する。

app/assets/stylesheets/application.scss
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

@import 'bootstrap';
@import 'custom';
#追記
@import 'flag-icon';

③ viewに記述する

あとは、表示したい箇所にspanタグで表示するだけ!

#〇〇はその国の略号が入ります。(日本→jp)
<span class="flag-icon flag-icon-○○"></span>

略号がリスト化されているもの、一応載せておきます。
ISO 3166-1

自分は日本の国旗を使用しました。

<span class="flag-icon flag-icon-jp"></span>

④ 大きさを変える

大きさは、font-sizeで変更できます。
ちなみに自分は、背景色が白のviewで使いたかったので、borderを使いましたが、この辺は用途に合わせて使っていきたいですね。

span {
      font-size: 100px;
      border: solid 1px  black;
      }

以上で完了です。

Flag Icon CSSとFont Awesome

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails] データベースに変更を加える手順

Progate学習メモ

1. マイグレーションファイル(だけ)を作成

rails g migration マイグレーションファイル名

Usersテーブルにimage_nameというカラムを追加させたい時は、
rails g migration add_image_name_to_users
という感じに

2. マイグレーションファイルのchangeメソッドに変更内容を書く

class AddImageNameToUsers < ActiveRecord::Migration[5.0]

  def change
    # ここに変更内容を書く
    # add_column :テーブル名, :カラム名, :データ型 
    add_column :users, :image_name, :string
  end
end

3. マイグレーションファイルの内容をデータベースに反映させる

rails db:migrate

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

jqueryでsubmitボタンを毎回有効にする方法

テックキャンプでJavaScriptの学習中に学んだ事

jQueryを使って非同期通信の学習をしている最後に、送信ボタンを押してイベント発火後に
送信ボタンが無効化されているのを有効にする方法を記します。

$('#hoge').prop('disabled', false);

調べてみてわかった事は

  • Railsのver5.0以降はdisabledがデフォルトで設定されている事(連打防止等の為)
  • 他にも有効に出来る方法はある

例えば

$('#hoge').attr('disabled', false);

自分のコードで試したが、どちらでも有効でした

今度は連打防止などの方法も調べて使え様にしていきます

非同期通信が自由に扱える様になると、少ないビューファイルの中に沢山の動的要素を
取り入れる事が出来て、かつレスポンスも早そうなので、プログラミングを学びたての自分でも
魅力的だなって感じました。

難しいけど面白い

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Rails 基礎的なCRUD機能実装手順 scaffold

前置き

Ruby on Railsを使って、基礎的なCRUD機能を実装する手順をまとめる。
CRUDとはCreate、Read、Update、Destroyの頭文字を取った用語。

アプリ立ち上げ

ターミナルで、railsコマンドを使って、アプリを作成する。

rails new blog_app -d postgresql

このコマンドだと、新しくblog_appを作成している。
使い慣れているので、データベースはpostgreSQLにしている。何も指定しない場合、sqlite3がデータベースになる。その後、アプリのルートディレクトリに移動(cd blog_app)し、ターミナルで

rails db:create

を入力し、データベースを立ち上げる。
サーバーを立ち上げて、アプリが出来ていることをローカルで確認する。

rails s

rails.PNG

上の画面が出ればOK。ctrl+Cでサーバーの立ち上げを終了できる。

CRUD機能

アプリが立ち上げられたので、ブログを投稿(create)、読み取り(read)、更新(update)、削除(delete)できる機能を実装する。
実は、railsジェネレーターのscaffoldを使うとコマンド2つで完了する。

rails g scaffold blog title:string content:text
rails db:migrate

最初のコマンドで、Blogモデル、ビュー、コントローラーとルーターの作成が一気にできる。この場合、Blogモデルに、string(文字列)型のインスタンス変数titleと、text(文章)型のインスタンス変数contentを作成している。
2つ目のコマンドは、データベースにblogsテーブルを作成するために必要。

後書き

今度は、scaffoldを使わずにモデル、ビュー、コントローラーとルーターのコードについてまとめようと思います。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Rails】CSVインポート機能の実装

目標

ezgif.com-video-to-gif.gif

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
Bootstrap3導入
投稿機能実装

実装

1.Gemを導入

Gemfile
# 追記
gem 'roo'
ターミナル
$ bundle

2.application.rbを編集

application.rb
require_relative 'boot'

require 'rails/all'
require 'csv' # 追記

Bundler.require(*Rails.groups)

module Bookers2Debug
  class Application < Rails::Application
    config.load_defaults 5.2
  end
end

3.モデル編集

book.rb
def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    book = find_by(id: row["id"]) || new
    book.attributes = row.to_hash.slice(*updatable_attributes)
    book.save!(validate: false)
  end
end

def self.updatable_attributes
  ['id', 'title', 'body']
end

① インポートするデータに同じIDが見つかればそのレコードを呼び出し、見つかれなければ新しく作成する。

book = find_by(id: row["id"]) || new

② CSVファイルからデータを取得する。

book.attributes = row.to_hash.slice(*updatable_attributes)

③ バリデーションを通さずに保存する。

book.save!(validate: false)

④ CSVインポート時に受信するカラムを設定する。

def self.updatable_attributes
  ['id', 'title', 'body']
end

4.コントローラーを編集

books_controller.rb
def import
  Book.import(params[:file])
  redirect_to books_path
end

5.ルーティングを追加

routes.rb
resources :books do
  collection { post :import }
end

6.ビューを編集

books/index.html.slim
= form_tag import_books_path, multipart: true do
  = file_field_tag :file
  br
  = submit_tag "インポート", class: 'btn btn-success'
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【日本語化】 i18n rails 楽々日本語化 viewの表示のみ

【ゴール】

viewだけ日本語表示へと切り替え

【メリット】

■ UIの向上
■ 日本語なので可読性向上し、開発効率化

【開発環境】

■ Mac OS catalina
■ Ruby on Rails (5.2.4.2)
■ Virtual Box:6.1
■ Vagrant: 2.2.7

【実装】

アプリケーション作成

※ touchでfileを作成

mac.terminal
$ rails new japoanese
$ rails g controller homes index
$ cd config/locale
$ touch ja.yml

※下記追記後 bundle install

gemfile.追加
gem 'rails-i18n', '~> 5.1' 

※ホーム画面へhomes/indexを!!

routes.rb
root 'homes#index'

※インデント要注意、

locale/ja.yml
ja:
 homes:
    index:
      title: '題名'
      name: ’名前’
      text: ’文章’

## modelが関連すると書き方少し変化します。下記みたいな感じです。。。

  activerecord:
    models:
      user: "ユーザー"
      attributes:
        user:
        name: "名前"
        age: "年齢"

下記重要

config/application.rb
config.i18n.default_locale = :ja #追加

※ja.ymlで定義」したものを引っ張ってきます。

homes/index.htmnl.erb
<h2><%= t '.title'%></h2>
<h2><%= t '.name'%></h2>
<h2><%= t '.text'%></h2>

以上!!

【合わせて読みたい】

■もっと詳しい記事
https://qiita.com/shimadama/items/7e5c3d75c9a9f51abdd5

■エラーメッセージ
https://qiita.com/tanaka-yu3/items/63b189d3f15653cae263

■rails メソッド 初学者者向け
https://qiita.com/tanaka-yu3/items/89abad875187494bec53

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

RailsとVueのアプリでbin/webpackできない

Vueを導入したRails6アプリでbin/webpackがエラーになったのでメモ。
これはアプリの初期段階で行ったもので、色々変わっても問題ない状況で試したことです。
なのでもう実装が進んでる方の場合は気をつけてください。

bin/webpackを実行したら、

error Command "webpack" not found.

というエラーが出た。

なぜかはわからないが、

yarn add webpack

でwebpackをインストール。

再度bin/webpackをすると、

One CLI for webpack must be installed.
--省略
Do you want to install 'webpack-cli' (yes/no):

と出たので、yesでwebpack-cliをインストール。

再度bin/webpackすると、

Error: Cannot find module '@rails/webpacker'

というエラー。

bin/rails webpacker:install

これでwebpackerを再度インストール。

bin/webpackで確認すると

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

というエラー。

とりあえず、Vueとwebpackerを合わせるために

rails webpacker:install:vue

を実行。

再度bin/webpack

Error: vue-loader requires @vue/compiler-sfc to be present in the dependency tree.

というエラー。

yarn add @vue/compiler-sfc 

これを実行した後に、bin/webpackを試したら実行できた。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【学習メモ】ぶち当たったエラー集 RailsアプリをHerokuへのデプロイ

目次

  • 背景
  • 実装環境
  • ぶち当たったエラー
  • 学び
  • 参考
  • 今回のエラーメッセージ(修正前)

背景

ポートフォリオを、仮の状態でもいいからデプロイしてWebサイトに公開することを挑戦。しかし幾度のエラーに直面して心折れそうになったが、問題解決できたので、その過程を整理して自分で理解し直す目的と、同じような躓きをしてしまった方のためにも、参考材料となればと思い、公開します。

実装環境

ぶち当たったエラー

1.Your Gemfile lists the gem pg (>= 0.18, < 2.0) more than once.

git push heroku masterしたログを辿ってみると、、、

terminal
(省略)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Ruby app detected
remote: -----> Installing bundler 2.0.2
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.6.5
remote: -----> Installing dependencies using bundler 2.0.2
remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
remote:        Your Gemfile lists the gem pg (>= 0.18, < 2.0) more than once.
remote:        You should probably keep only one of them.
remote:        Remove any duplicate entries and specify the gem only once (per group).
remote:        While it's not a problem now, it could cause errors if you change the version of one of them later.
(省略)

の中の、ここが問題。

terminal
remote:        Your Gemfile lists the gem pg (>= 0.18, < 2.0) more than once.
remote:        You should probably keep only one of them.

【意味】
Postgresqlが2つあるから、どちらか1つだけ残しておけよ(=1個消しなさい)

【これが発生した原因】
udemyの教材を参考に、自分で記述していたことに気づく。

group :production do
gem 'pg', '>= 0.18', '< 2.0'
end

【試したこと・実装方法】
デフォルトでPostgreSQL採用しているので上記コードを消去してgit commit。

#masterブランチにて
git add -A
git commit -m “Message”

で、この表示はなくなり解決。

2.remote: ! Precompiling assets failed.

【意味】
コンパイルの設定に失敗した

【原因】
コンパイルの設定を行うためのgem, コードがなかった

【試したこと・実装方法】
Qiita記事を参考に、下記の通り記述。

config/environments/production.rb
config.assets.initialize_on_precompile = false

これだけではうまく行かなかったので、上記コードをそのままググり、スタックオーバーフローの記事を発見。これを参考に、下記の通り記述。

config/environments/production.rb
  config.assets.js_compressor = :uglifier

Gemfile
gem 'uglifier'

これでこの問題について解決。

3.error: failed to push some refs to 'https://git.heroku.com/(アプリ名).git'

【意味】
エラー:一部の参照を、https:(アプリ名).gitへのpushできなかった

【原因】
リモートとローカルでコミットが分かれてしまい単純にはマージできない状況になってしまったため(その状況が起こるのは、ローカルでcommitしたけどリモートにpushし忘れた、場合が考えられそう

【試したこと・実装方法】
VScodeでCommit履歴を確認。ローカルリポジトリのブランチXを、マスターブランチにmergeし、リモートリポジトリにpull requestして、git merge ブランチXを実行。

実行できたことを確認し、1.,2.の問題が片付いた上で、

terminal
bundle install
git add -A
git commit -m “Message”
git push heroku master

したところ、、、

terminal
(省略)
remote:        https://quiet-escarpment-59252.herokuapp.com/ deployed to Heroku
remote: 
remote: Verifying deploy... done.
To https://git.heroku.com/quiet-escarpment-59252.git
 * [new branch]      master -> master

そして、

terminal
user$ heroku run rails db:migrate

学び

今まで、目に見えてエラーと表示されている箇所ばかりログを読んでいたのですが、実行された内容全部確認してみると、「目立ってないけど実はエラーなんです」という内容が結構あるんだなぁと気付きました。

そして、ログを辿りながら「ん?」ってなったところを上から徹底的に調査して1つずつ潰していくのが(基本中の基本ですが)大事だと学びました。

某現役エンジニアの方曰く「上から順に潰していくゲームだ」とおっしゃっていました。地道な作業ですが、ゲーム感覚で楽しみながら今後も開発していきたいと思います。

参考

Herokuにpushしたらprecompile assets faild.が。pushできたと思ったらApplication Errorが。解決するまで。

git push時にerror: failed to push some refs toとエラーがでる

git push heroku masterで発生するエラー( Precompiling assets failed., error: failed to push some refs to)について

heroku git push heroku masterが拒まれた話

Heroku build fails on uglifier

our Gemfile lists the gem more than once. could cause errors

Heroku:Buildpackエラーでハマった

今回のエラーメッセージ(修正前) ※超長文のため注意

terminal
USER:[アプリ名] user$ git push heroku master
Enumerating objects: 209, done.
Counting objects: 100% (209/209), done.
Delta compression using up to 8 threads
Compressing objects: 100% (178/178), done.
Writing objects: 100% (209/209), 181.92 KiB | 7.28 MiB/s, done.
Total 209 (delta 29), reused 105 (delta 11)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Ruby app detected
remote: -----> Installing bundler 2.0.2
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.6.5
remote: -----> Installing dependencies using bundler 2.0.2
remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
remote:        Your Gemfile lists the gem pg (>= 0.18, < 2.0) more than once.
remote:        You should probably keep only one of them.
remote:        Remove any duplicate entries and specify the gem only once (per group).
remote:        While it's not a problem now, it could cause errors if you change the version of one of them later.
remote:        The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
remote:        Fetching gem metadata from https://rubygems.org/.........
remote:        Fetching rake 13.0.1
remote:        Installing rake 13.0.1
remote:        Fetching concurrent-ruby 1.1.6
remote:        Fetching minitest 5.14.1
remote:        Fetching thread_safe 0.3.6
remote:        Installing thread_safe 0.3.6
remote:        Installing concurrent-ruby 1.1.6
remote:        Installing minitest 5.14.1
remote:        Fetching builder 3.2.4
remote:        Fetching erubi 1.9.0
remote:        Installing builder 3.2.4
remote:        Installing erubi 1.9.0
remote:        Fetching mini_portile2 2.4.0
remote:        Installing mini_portile2 2.4.0
remote:        Fetching crass 1.0.6
remote:        Installing crass 1.0.6
remote:        Fetching rack 2.2.2
remote:        Fetching nio4r 2.5.2
remote:        Installing rack 2.2.2
remote:        Installing nio4r 2.5.2 with native extensions
remote:        Fetching websocket-extensions 0.1.5
remote:        Installing websocket-extensions 0.1.5
remote:        Fetching mini_mime 1.0.2
remote:        Installing mini_mime 1.0.2
remote:        Fetching arel 9.0.0
remote:        Installing arel 9.0.0
remote:        Fetching mimemagic 0.3.5
remote:        Installing mimemagic 0.3.5
remote:        Fetching execjs 2.7.0
remote:        Installing execjs 2.7.0
remote:        Fetching bcrypt 3.1.13
remote:        Fetching msgpack 1.3.3
remote:        Installing bcrypt 3.1.13 with native extensions
remote:        Installing msgpack 1.3.3 with native extensions
remote:        Fetching popper_js 1.16.0
remote:        Installing popper_js 1.16.0
remote:        Fetching method_source 1.0.0
remote:        Installing method_source 1.0.0
remote:        Fetching thor 1.0.1
remote:        Installing thor 1.0.1
remote:        Fetching ffi 1.13.0
remote:        Installing ffi 1.13.0 with native extensions
remote:        Fetching tilt 2.0.10
remote:        Installing tilt 2.0.10
remote:        Using bundler 2.0.2
remote:        Fetching cocoon 1.2.14
remote:        Installing cocoon 1.2.14
remote:        Fetching coderay 1.1.3
remote:        Installing coderay 1.1.3
remote:        Fetching orm_adapter 0.5.0
remote:        Installing orm_adapter 0.5.0
remote:        Fetching devise-bootstrap-views 1.1.0
remote:        Installing devise-bootstrap-views 1.1.0
remote:        Fetching devise-i18n-views 0.3.7
remote:        Installing devise-i18n-views 0.3.7
remote:        Fetching multi_json 1.14.1
remote:        Installing multi_json 1.14.1
remote:        Fetching hpricot 0.8.6
remote:        Installing hpricot 0.8.6 with native extensions
remote:        Fetching kaminari-core 1.2.1
remote:        Installing kaminari-core 1.2.1
remote:        Fetching pg 1.2.3
remote:        Installing pg 1.2.3 with native extensions
remote:        Fetching temple 0.8.2
remote:        Installing temple 0.8.2
remote:        Fetching turbolinks-source 5.2.0
remote:        Installing turbolinks-source 5.2.0
remote:        Fetching tzinfo 1.2.7
remote:        Installing tzinfo 1.2.7
remote:        Fetching nokogiri 1.10.9
remote:        Installing nokogiri 1.10.9 with native extensions
remote:        Fetching i18n 1.8.2
remote:        Installing i18n 1.8.2
remote:        Fetching websocket-driver 0.7.2
remote:        Installing websocket-driver 0.7.2 with native extensions
remote:        Fetching mail 2.7.1
remote:        Installing mail 2.7.1
remote:        Fetching rack-test 1.1.0
remote:        Installing rack-test 1.1.0
remote:        Fetching sprockets 4.0.0
remote:        Installing sprockets 4.0.0
remote:        Fetching warden 1.2.8
remote:        Installing warden 1.2.8
remote:        Fetching request_store 1.5.0
remote:        Installing request_store 1.5.0
remote:        Fetching rack-proxy 0.6.5
remote:        Installing rack-proxy 0.6.5
remote:        Fetching marcel 0.3.3
remote:        Installing marcel 0.3.3
remote:        Fetching autoprefixer-rails 9.7.6
remote:        Installing autoprefixer-rails 9.7.6
remote:        Fetching puma 4.3.5
remote:        Installing puma 4.3.5 with native extensions
remote:        Fetching pry 0.13.1
remote:        Installing pry 0.13.1
remote:        Fetching bootsnap 1.4.6
remote:        Installing bootsnap 1.4.6 with native extensions
remote:        Fetching sassc 2.3.0
remote:        Installing sassc 2.3.0 with native extensions
remote:        Fetching slim 4.1.0
remote:        Installing slim 4.1.0
remote:        Fetching turbolinks 5.2.1
remote:        Installing turbolinks 5.2.1
remote:        Fetching activesupport 5.2.4.3
remote:        Installing activesupport 5.2.4.3
remote:        Fetching html2slim 0.2.0
remote:        Fetching loofah 2.5.0
remote:        Installing loofah 2.5.0
remote:        Installing html2slim 0.2.0
remote:        Fetching pry-rails 0.3.9
remote:        Installing pry-rails 0.3.9
remote:        Fetching rails-dom-testing 2.0.3
remote:        Installing rails-dom-testing 2.0.3
remote:        Fetching globalid 0.4.2
remote:        Installing globalid 0.4.2
remote:        Fetching activemodel 5.2.4.3
remote:        Installing activemodel 5.2.4.3
remote:        Fetching jbuilder 2.10.0
remote:        Installing jbuilder 2.10.0
remote:        Fetching rails-html-sanitizer 1.3.0
remote:        Fetching activejob 5.2.4.3
remote:        Installing rails-html-sanitizer 1.3.0
remote:        Installing activejob 5.2.4.3
remote:        Fetching activerecord 5.2.4.3
remote:        Installing activerecord 5.2.4.3
remote:        Fetching actionview 5.2.4.3
remote:        Installing actionview 5.2.4.3
remote:        Fetching actionpack 5.2.4.3
remote:        Installing actionpack 5.2.4.3
remote:        Fetching kaminari-actionview 1.2.1
remote:        Installing kaminari-actionview 1.2.1
remote:        Fetching kaminari-activerecord 1.2.1
remote:        Installing kaminari-activerecord 1.2.1
remote:        Fetching polyamorous 2.3.2
remote:        Installing polyamorous 2.3.2
remote:        Fetching kaminari 1.2.1
remote:        Installing kaminari 1.2.1
remote:        Fetching ransack 2.3.2
remote:        Installing ransack 2.3.2
remote:        Fetching actioncable 5.2.4.3
remote:        Installing actioncable 5.2.4.3
remote:        Fetching actionmailer 5.2.4.3
remote:        Installing actionmailer 5.2.4.3
remote:        Fetching activestorage 5.2.4.3
remote:        Fetching railties 5.2.4.3
remote:        Installing activestorage 5.2.4.3
remote:        Installing railties 5.2.4.3
remote:        Fetching sprockets-rails 3.2.1
remote:        Installing sprockets-rails 3.2.1
remote:        Fetching gon 6.3.2
remote:        Installing gon 6.3.2
remote:        Fetching chart-js-rails 0.1.7
remote:        Fetching responders 3.0.1
remote:        Installing responders 3.0.1
remote:        Installing chart-js-rails 0.1.7
remote:        Fetching jquery-rails 4.4.0
remote:        Fetching rails 5.2.4.3
remote:        Installing rails 5.2.4.3
remote:        Fetching momentjs-rails 2.20.1
remote:        Installing jquery-rails 4.4.0
remote:        Installing momentjs-rails 2.20.1
remote:        Fetching rails-i18n 5.1.3
remote:        Installing rails-i18n 5.1.3
remote:        Fetching slim-rails 3.2.0
remote:        Installing slim-rails 3.2.0
remote:        Fetching webpacker 4.2.2
remote:        Installing webpacker 4.2.2
remote:        Fetching devise 4.7.1
remote:        Installing devise 4.7.1
remote:        Fetching kaminari-bootstrap 3.0.1
remote:        Installing kaminari-bootstrap 3.0.1
remote:        Fetching devise-i18n 1.9.1
remote:        Installing devise-i18n 1.9.1
remote:        Fetching sassc-rails 2.1.2
remote:        Installing sassc-rails 2.1.2
remote:        Fetching bootstrap 4.5.0
remote:        Fetching sass-rails 6.0.0
remote:        Installing sass-rails 6.0.0
remote:        Installing bootstrap 4.5.0
remote:        Bundle complete! 38 Gemfile dependencies, 90 gems now installed.

remote:        Gems in the groups development and test were not installed.
remote:        Bundled gems are installed into `./vendor/bundle`
remote:        Post-install message from i18n:
remote:        
remote:        HEADS UP! i18n 1.1 changed fallbacks to exclude default locale.
remote:        But that may break your application.
remote:        
remote:        If you are upgrading your Rails application from an older version of Rails:
remote:        
remote:        Please check your Rails app for 'config.i18n.fallbacks = true'.
remote:        If you're using I18n (>= 1.1.0) and Rails (< 5.2.2), this should be
remote:        'config.i18n.fallbacks = [I18n.default_locale]'.
remote:        If not, fallbacks will be broken in your app by I18n 1.1.x.
remote:        
remote:        If you are starting a NEW Rails application, you can ignore this notice.
remote:        
remote:        For more info see:
remote:        https://github.com/svenfuchs/i18n/releases/tag/v1.1.0
remote:        
remote:        Bundle completed (234.22s)
remote:        Cleaning up the bundler cache.
remote: -----> Installing node-v10.15.3-linux-x64
remote: -----> Installing yarn-v1.16.0
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        yarn install v1.16.0
remote:        [1/4] Resolving packages...
remote:        [2/4] Fetching packages...
remote:        info fsevents@2.1.3: The platform "linux" is incompatible with this module.
remote:        info "fsevents@2.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
remote:        info fsevents@1.2.13: The platform "linux" is incompatible with this module.
remote:        info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
remote:        [3/4] Linking dependencies...
remote:        warning " > webpack-dev-server@3.11.0" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
remote:        warning "webpack-dev-server > webpack-dev-middleware@3.7.2" has unmet peer dependency "webpack@^4.0.0".
remote:        [4/4] Building fresh packages...
remote:        Done in 27.11s.
remote:        yarn install v1.16.0
remote:        [1/4] Resolving packages...
remote:        [2/4] Fetching packages...
remote:        info fsevents@2.1.3: The platform "linux" is incompatible with this module.
remote:        info "fsevents@2.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
remote:        info fsevents@1.2.13: The platform "linux" is incompatible with this module.
remote:        info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
remote:        [3/4] Linking dependencies...
remote:        warning " > webpack-dev-server@3.11.0" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
remote:        warning "webpack-dev-server > webpack-dev-middleware@3.7.2" has unmet peer dependency "webpack@^4.0.0".
remote:        [4/4] Building fresh packages...
remote:        Done in 5.73s.
remote:        rake aborted!
remote:        LoadError: cannot load such file -- uglifier

remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:34:in `require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:291:in `block in require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:257:in `load_dependency'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:291:in `require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/autoload/uglifier.rb:2:in `<main>'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:291:in `block in require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:257:in `load_dependency'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4.3/lib/active_support/dependencies.rb:291:in `require'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/uglifier_compressor.rb:43:in `initialize
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/uglifier_compressor.rb:26:in `new'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/uglifier_compressor.rb:26:in `instance'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/uglifier_compressor.rb:30:in `call'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:84:in `call_processor
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:66:in `block in call_processors'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:65:in `reverse_each'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:65:in `call_processors'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:182:in `load_from_unloaded'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:59:in `block in load'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:335:in `fetch_asset_from_dependency_cache'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:43:in `load'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/cached_environment.rb:44:in `load'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/bundle.rb:32:in `block in call'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/bundle.rb:31:in `call'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:84:in `call_processor
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:66:in `block in call_processors'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:65:in `reverse_each'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/processor_utils.rb:65:in `call_processors'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:182:in `load_from_unloaded'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:59:in `block in load'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:335:in `fetch_asset_from_dependency_cache'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/loader.rb:43:in `load'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/cached_environment.rb:44:in `load'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/base.rb:81:in `find_asset'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/base.rb:88:in `find_all_linked_assets'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.0/lib/sprockets/manifest.rb:125:in `block (2 levels) in find'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/safe_task_executor.rb:24:in `block in execute'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb:41:in `block in synchronize'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb:41:in `synchronize'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb:41:in `synchronize'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/safe_task_executor.rb:19:in `execute'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/promise.rb:563:in `block in realize'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb:353:in `run_task'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb:342:in `block (3 levels) in create_worker'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb:325:in `loop'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb:325:in `block (2 levels) in create_worker'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb:324:in `catch'
remote:        /tmp/build_766ffab2466e42f825b9e77071bc1f96/vendor/bundle/ruby/2.6.0/gems/concurrent-ruby-1.1.6/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb:324:in `block in create_worker'
remote:        Tasks: TOP => assets:precompile
remote:        (See full trace by running task with --trace)
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !       Push rejected to [アプリ名]
remote: 
To https://git.heroku.com/[アプリ名].git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to '[アプリ名].git'
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

deviseの使い方 導入から設定変更

はじめに

勉強のためにdeviseを使い、ログイン周りを作成しました。
デフォルトではユーザー名、パスワードで認証しますが、今回社員番号、パスワードで認証するよう設定を変更していきます。

環境

Ruby 2.5.3
Ruby on Rails 5.2.4
Devise 4.7.1

完成

スクリーンショット 2020-06-24 16.00.39.png
スクリーンショット 2020-06-24 16.00.56.png
bootstrapで見た目を整えていますが、このようになるように設定を変更していきます。

実装

Gemfile
gem 'devise'
$ bundle install

●deviseの設定

$ rails generate devise:install

こんな感じのメッセージがでます。
初心者なのでエラーメッセージかとびっくりしましたが、これが出れば成功です。

create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here
    is an example of default_url_options appropriate for a development environment
    in config/environments/development.rb:

    config.action_mailer.default_url_options = { :host => 'localhost:3000' }

    In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
    For example:

    root :to => "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
    For example:

    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>

  4. You can copy Devise views (for customization) to your app by running:

    rails g devise:views

===============================================================================

●メッセージの内容
1.新規登録など認証メールを送った際に、メールの文中にある承認リンクURLを設定します。

config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

2.ルート設定
会員登録後などにルートに飛ぶ設定になっています。

3.フラッシュメッセージを埋め込みます。ログイン、ログアウトの際にフラッシュを表示させたい時に使用します。私は共通ビューに埋め込みました。

app/views/layouts/application.html.erb
<body>
 <p class="notice"><%= notice %></p>
 <p class="alert"><%= alert %></p>
</body>

4.ビューのカスタマイズをするために

$ rails g devise:views

●deviseの設定変更

config/initializers/devise.rb
43行目あたり
認証キーは社員番号を指定
- config.authentication_keys = [:email]
+ config.authentication_keys = [:employee_number]
55行目あたり
認証キーの値は大文字小文字を区別しない
- config.case_insensitive_keys = [:email]
+ config.case_insensitive_keys = [:employee_number]
60行目あたり
空白キーを取り除く
- config.strip_whitespace_keys = [:email]
+ config.strip_whitespace_keys = [:employee_number]

●ユーザーモデルを作る

$ rails g devise user
app/models/user.rb
# 以下3つのメソッドは、user名を認証キーとするので、
# 不必要なメソッドをオーバーライドして無効化しています。

def email_required?
    false
  end

  def email_changed?
    false
  end

  def will_save_change_to_email?
    false
  end

db/migrate/日付_devise_create_user.rb
class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :employee_number,    null: false, default: ""
      t.string :encrypted_password, null: false, default: ""
## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.string   :current_sign_in_ip
      # t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at
    t.timestamps null: false
    end

     ここを変更!!
     - add_index :users, :email,      unique: true
     + add_index :users, :employee_number,      unique: true
      add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end
$ rials db:migrate

●コントローラーの変更

application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  # methodをオーバーライドする。
  def configure_permitted_parameters
    sign_up_params = [:employee_number, :password, :password_confirmation]
    sign_in_params = [:employee_number, :password, :remember_me] 

      # account_update, sign_in, sign_up, のフィールドを再定義
    devise_parameter_sanitizer.permit(:sign_up, keys: sign_up_params)
    devise_parameter_sanitizer.permit(:sign_in, keys: sign_in_params)
    devise_parameter_sanitizer.permit(:account_update, keys: account_update)
  end
 end

設定はこれで終わりです。あとはviewを変更すれば完成です。

参考

[Rails] deviseの使い方(rails5版)
Ruby on Rails 初心者が gem Devise 使ってみた。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails] エラーメッセージ を表示する - render、redirect_toの違い、flashについて -

エラーメッセージを表示する方法について書きます。
Railsでメッセージ出力する際によく使用されるrender、redirect_to、flashについても簡単に書きます。

実装したいこと

フォームの入力値に誤りがあるときに、以下のようなエラーメッセージを表示させる
image.png

実装したコード

login_controller.rb
    @error_txt = '※入力に誤りがあるか、登録されていません。'
    render :new

インスタンス変数@error_txtにエラーメッセージをセットし、renderでテンプレートnewを表示させるように指定します。
※エラー判定の処理は省略しています

new.html.slim
    - if @error_txt
        p.error
            = @error_txt

テンプレート側ではインスタンス変数の@error_txtの値の存在チェックを行い、あれば@error_txtを表示させます。

renderとは

renderとはテンプレートを指定して表示させる(レンダリングする)ためのメソッドです。
画面遷移させることなく、表示させることができます。

redirect_toとの違い

renderと同様にページを指定して表示させるメソッドにredirect_toがあります。
renderが画面遷移することなく指定したテンプレートを表示するのに対して、
redirect_toメソッドはリダイレクトさせるためのメソッドで、URLを指定してリクエストを再送信するようにブラウザに指令を出します。
ブラウザはこの指令に応じ、指定されたURLに対して改めてリクエストをサーバーに送信します。
ブラウザとサーバー間のやりとりや処理が増えるため、改めてリクエストを送信させる必要がない場合は、renderを使うのが良いです。

今回はフォームの入力内容に対してエラーメッセージを表示させるだけで、リダイレクトさせたくないためrenderを使用します。

flashとは

railsにおけるメッセージ表示について調べるとflashに関する記事が多くでてきます。
flashはsessionを利用した機能の一つでメッセージを画面に表示するためのメソッドです。
flashで設定したメッセージはセッションに保存され、リダイレクトされても保持されるためredirect_toメソッドを一緒に使うことが多いです。

今回はrenderを使用しており、リダイレクトもなく、セッションに値を保持する必要がないのでflashを使わずにインスタンス変数を使いました。

まとめ

  • リダイレクト不要なエラーメッセージはrenderとインスタンス変数で実装する
  • リダイレクトが必要な場合は、redirect_toとflashで実装する
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails] バリデーションの書き方

Progate学習メモ

models/post.rb
class Post < ApplicationRecord

  validates :検証するカラム名, {検証する内容}

end

色々なバリデーション

カラムが存在するかどうか
validates :content, {presence: true}

最大140文字まで受け付ける
validates :content, {length: {maximum: 140}}

重複がないか
validates :email, {uniqueness: true}

バリデーションをまとめて書く

models.post.rb
class Post < ApprocationRecord

  validates :content, {presence: true, length: {maximum: 140}}

end
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

railsでDATABASE_URLを使う際の注意点

概要

環境変数のDATABASE_URLを使うとユーザー名やパスワードなど複数の項目を1つの環境変数で指定出来て便利です。
しかしハマりポイントもあるのでDATABASE_URLを使う際の注意点を紹介します。
なお本番環境にはあまり関係ない話です。

投稿時点でのrailsのバージョンは6.0.3.2です。

優先順位について

database設定の優先順位は下記の通りです。

  1. database.ymlのurl項目
  2. 環境変数DATABASE_URL
  3. database.yml

参考url
https://railsguides.jp/configuring.html#%E6%8E%A5%E7%B6%9A%E8%A8%AD%E5%AE%9A

DATABASE_URLが使われるのは現在のRAILS_ENVだけ

DATABASE_URLが使われるのは現在のRAILS_ENVだけのようです。
しかしRAILS_ENVがdevelopmentの場合はtestに対してもtaskが実行されます。
そのためdevelopmentで db:create を行うとtestに対しても db:create が実行されますがtestではDATABASE_URLを参照されないため失敗するなどといった問題が発生します。

回避策としてはdatabase.ymlのurlでDATABASE_URLを使うように明示的に指定する方法があります。
ただしこれも今後は注意が必要そうです。

今後の注意点

上記の問題修正のためにDATABASE_URLが設定されていた場合はRAILS_ENVがdevelopmentでもtestに対してtaskを実行しない修正が行われました。
すでにmasterにはマージ済みでおそらく6.1でリリースされると思われます。

https://github.com/rails/rails/pull/37351

現在developmentでDATABASE_URLを使っている場合はdevelopmentとtestでdatabaseのズレが発生するようになることが予想されます。
今後はtest環境で別途手動でtaskを実行するのを忘れない、もしくはそもそもdevelopmentではDATABASE_URLを使わないなどの対応が必要そうです。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

dockerとmysqlでrails環境を構築した

dockerにrails環境を作った
https://qiita.com/NA_simple/items/5e7f95ae58eec5d20e1f

途中なぜか上手くいかないと思ったら、mysql-clientsがインストールできなくなっているらしい。書き換え方は下のURLを参考に。
https://qiita.com/yagi_eng/items/1368fb2a234629a0c8e7

調子に乗ってすすめていると、またハマる。

terminal
$ docker-compose run web rails db:create
Starting postgress_db ... done
Could not find activesupport-5.2.4.3 in any of the sources
Run `bundle install` to install missing gems.

なぜだ、、、と思ったらrubyのバージョンが違う??
rbenvでバージョンを探しても、2.7.1が見つからず。
rbenv古い事に気づき、アップデート

rbenvをアップデート
https://qiita.com/pugiemonn/items/f277440ec260b8d4fa6a

からのgemも古い事に気づき、

terminal
$ gem update

まだいかない、、、
bundler updateを行う。

ここらへんで絶望したので時間を置く。

一旦整理して、違うサイトの最初から手順をパクる。

https://toranoana-lab.hatenablog.com/entry/2020/06/05/173658

なんと止まること無くdockerの起動、localhostにアクセス可能に!!!
よっしゃ!!!!

localhost_3000
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

なんで :D
ググるとファイルが無いらしいからsudo touchで無理やり作ってる記事がちらほら。
でもファイルあるしなあ、と思いつつ削除&作成

同じエラー。

???と思い、ここでmysql立ち上げていないことに気づく
これだ!!!と思って

terminal
mysql.server start

を実行するも、起動しない。
ググるとどうやら

terminal
sudo rm mysql.sock
brew uninstall mysql
brew install mysql

と、sockファイルを消してからmysqlをアンインストール→インストールで治るらしい。
mysql.sockのパスは前のエラーで判明していたので、それを消してから

terminal
mysql.server start

…通った!!!!

これは行ったか…?

image.png

ヤッターーーーーーー!!!!!!!!!

docker理解してから構築したほうが早かったと思います。
勉強し直しましょう。自分。

なにはともあれ動いてよかった

最終的な各ファイルの中身↓

gemfile
source 'https://rubygems.org'
gem 'rails', '~>6'
docker-compose.yml
version: '3'
services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD:
    ports:
      - '3306:3306'
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - mysql-data:/var/lib/mysql
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
    stdin_open: true
    tty: true
    command: bundle exec rails server -b 0.0.0.0
volumes:
  mysql-data:
    driver: local
Dockerfile
FROM ruby:2.7
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
    && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
    && apt-get update -qq \
    && apt-get install -y nodejs yarn \
    && mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

dockerとmysqlでrails環境を構築したけどドハマリした

dockerにrails環境を作った
https://qiita.com/NA_simple/items/5e7f95ae58eec5d20e1f

途中なぜか上手くいかないと思ったら、mysql-clientsがインストールできなくなっているらしい。書き換え方は下のURLを参考に。
https://qiita.com/yagi_eng/items/1368fb2a234629a0c8e7

調子に乗ってすすめていると、またハマる。

terminal
$ docker-compose run web rails db:create
Starting postgress_db ... done
Could not find activesupport-5.2.4.3 in any of the sources
Run `bundle install` to install missing gems.

なぜだ、、、と思ったらrubyのバージョンが違う??
rbenvでバージョンを探しても、2.7.1が見つからず。
rbenv古い事に気づき、アップデート

rbenvをアップデート
https://qiita.com/pugiemonn/items/f277440ec260b8d4fa6a

からのgemも古い事に気づき、

terminal
$ gem update

まだいかない、、、
bundler updateを行う。

ここらへんで絶望したので時間を置く。

一旦整理して、違うサイトの最初から手順をパクる。

https://toranoana-lab.hatenablog.com/entry/2020/06/05/173658

なんと止まること無くdockerの起動、localhostにアクセス可能に!!!
よっしゃ!!!!

localhost_3000
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

なんで :D
ググるとファイルが無いらしいからsudo touchで無理やり作ってる記事がちらほら。
でもファイルあるしなあ、と思いつつ削除&作成

同じエラー。

???と思い、ここでmysql立ち上げていないことに気づく
これだ!!!と思って

terminal
mysql.server start

を実行するも、起動しない。
ググるとどうやら

terminal
sudo rm mysql.sock
brew uninstall mysql
brew install mysql

と、sockファイルを消してからmysqlをアンインストール→インストールで治るらしい。
mysql.sockのパスは前のエラーで判明していたので、それを消してから

terminal
mysql.server start

…通った!!!!

これは行ったか…?

image.png

ヤッターーーーーーー!!!!!!!!!

docker理解してから構築したほうが早かったと思います。
勉強し直しましょう。自分。

なにはともあれ動いてよかった

最終的な各ファイルの中身↓

gemfile
source 'https://rubygems.org'
gem 'rails', '~>6'
docker-compose.yml
version: '3'
services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD:
    ports:
      - '3306:3306'
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - mysql-data:/var/lib/mysql
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
    stdin_open: true
    tty: true
    command: bundle exec rails server -b 0.0.0.0
volumes:
  mysql-data:
    driver: local
Dockerfile
FROM ruby:2.7
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
    && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
    && apt-get update -qq \
    && apt-get install -y nodejs yarn \
    && mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む