20210730のRailsに関する記事は22件です。

Rails×Reactアプリをクローンした後の環境構築について。

Rails×Reactで構成されたアプリケーションに対して git clone した後、環境構築しようとした際に、ものすごく時間がかかったので、同じミスをしないようにメモしておく。 結論 ()は必要に応じて ① Nodeのバージョンを指定 (② .nvmrcに希望のバージョンを指定) (③ .gitignoreに .nvmrcを追加) ④ gemfile.lock削除 ⑤ Railsのバージョンを指定 ⑥ Bundle install ⑦ Rails db:create ⑧ Rails db:migrate ⑨ npm ci ⑩ yarn -v(→ yarnがインストールされていなければ yarn install) ( rails webpacker:compile) ①について まずlatestなNodeを使用するとnode-gypのエラーが後々発生する可能性があるので、出来ればstableなバージョンをインストールして使用するべき。 (npmは基本自動で変更されるので合わせる必要なし) ②について 筆者は、Nodeバージョン管理にnvmを使用していたので以下のHPを参考にした。 引用:https://shinshin86.hateblo.jp/entry/2020/05/14/220149 ③について 今後gitでマージする際に、.nvmrcファイルをアップロードしないように、以下のソースコードをプロジェクト内の.gitignoreファイルに追加。 .gitignore /.nvmrc ④について 基本的にGemfile.lockを削除することは、基本的にNG。 だが、筆者がクローンしたプロジェクトは、mimemagic <= 0.3.5に依存しているRailsアプリであったため、どうしても⑤のbundle installに失敗してしまっていた。 以下のHP上での、「都合によりRailsをアップデートできない・したくない場合の操作」を実行しても、どうしても上手くいかなかったため、 ④→⑤の流れをするとなぜか上手くいった。 引用:https://hackmd.io/@mametter/mimemagic-info-ja ⑤について Gemfileにrailsのバージョンを指定。 ⑨について npm ciとは。 package-lock.json から依存関係をインストールするコマンド。 既に node_modules フォルダの中身があっても一旦削除してくれる。 依存関係の更新をせずに整合性チェックと依存パッケージのダウンロードのみを行い、 npm install より高速に動作し、CIで必要なことだけを行うのが、このコマンドである。 nodeを使用しているプロジェクトをgit cloneするときは、必ず必要になるコマンド 引用:https://qiita.com/mstssk/items/8759c71f328cab802670 ⑩について ローカルでサーバーを開いたときに、 ℹ 「wdm」: wait until bundle finished: / ...... などが出てきてフロント画面の描画が遅い時などは、このコマンドが必要になる場合がある。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

新規RailsプロジェクトをHerokuでデプロイするまでに最低限やることリスト12つ

はじめに RailsでアプリをつくってサクっとHerokuで公開するときに、とりあえずコピペでやっとくといいかもなリストです。 自分用の備忘録なので「あれもやったほうがいい!」とかはご容赦ください。 新しくRailsプロジェクトをつくる rails new <プロジェクト名> GitHubで履歴管理する 1. GitHubに新規リポジトリを作って接続 2. 空コミットする # リポジトリ作成 git init # 最初のコミット(空コミット) git commit --allow-empty -m "first commit" SQLiteからPostgresに変更 Rails6からコマンド1発ででいるようになったらしい。神。 #postgresqlに変更 rails db:system:change --to=postgresql # データベースをつくる createdb "dbname" # データベースの作成を完了させる rails db:create GemfileにGemを追加 自分がよく使うのはこんな感じ # for debug gem 'pry' # for design gem 'bootstrap' # use jQuery gem 'jquery-rails' gem 'jquery-turbolinks' # use font-awesome gem 'font-awesome-sass' # ogpの取得 gem 'open_uri_redirections' gem 'opengraph_parser' gem 'solargraph' # サイトマップを作る gem 'sitemap_generator' # sitemap自動更新用 gem 'whenever', require: false # 日本語対応 gem 'rails-i18n' # Slack通知(ユーザーからの投稿などがある場合は、Slack通知で不正なデータがないかチェック) gem 'slack-notifier' # Sentryでエラー検知 gem 'sentry-raven' # Kaminariでページング gem 'kaminari' bundle install jQueryを使えるようにする npm install --save jquery yarn install --check-files webpackをインストール rails webpacker:install サービスの根幹をつくる ・モデル作成 rails g model <モデル名> ・マイグレーションでカラム作成 rails g migration AddColumnTo<モデル名> rails db:migrate ・コントローラー作成 rails g controller <コントローラー名> ・ルーティング設定 config/routes.rb Rails.application.routes.draw do root 'results#index' # 存在しないページはトップページに飛ばす(これ最後に書かないとそこ以降は全部これに引っかかってとばされる…) get '*unmatched_route', to: 'results#index' end ・Viewのデザイン設定 集客、拡散させるためのコツ 画像の作成 ・Twitter用のカードをつくってassets/images配下に置く ・iPhoneでホーム画面に追加されるとき用のアイコン(apple-touch-icon.png)をつくってassets/images配下に置く ・faviconをつくってassets/images配下に置く ページのタイトル、説明、ogp画像を可変にする ・application helperで管理 app/views/layouts/application.html.erb <meta name="description" content="<%= page_description %>"> <meta property="og:title" content="<%= page_title %>"> <meta property="og:description" content="<%= page_description %>"> <meta property="og:url" content="<%= request.url %>"> <meta property="og:image" content="<%= page_image %>"> <meta name="twitter:card" content="summary_large_image"> <meta property="twitter:card" content="summary_large_image"> <meta name="twitter:image" content="<%= page_image %>"> app/helpers/application_helper.rb module ApplicationHelper def page_title title = "基本のタイトル" title = @page_title + " - " + title if @page_title title end def page_description description = "基本の説明" if @work description = "#{変数}と組み合わせたり" end description = @page_description.nil? ? description : @page_description end def page_image image = asset_url('基本のサムネイル')   # ページごとにサムネイルがあったら上書き if @works @works.each do |work| unless work&.thumbnail_url.blank? || work.nil? image = work&.thumbnail_url break end end end image end def get_twitter_card_info(page) twitter_card = {}   # ページごとにTwitterシェア時のサムネイルを変える if page twitter_card[:url] = page.url twitter_card[:title] = page.title twitter_card[:description] = page.description else twitter_card[:url] = '基本のURL' twitter_card[:title] = '基本のタイトル' twitter_card[:description] = '基本の説明' end twitter_card[:image] = asset_url('基本のサムネイル画像') twitter_card[:card] = 'summary_large_image' twitter_card[:site] = '@rubys8arks' twitter_card end end エラーページの作成 エラーメッセージの日本語化 locals配下にja.ymlを置く タイムゾーンの日本時間化 config/application.rb # デフォルトのタイムゾーンを日本にする config.time_zone = 'Tokyo' config.active_record.default_timezone = :local config.i18n.default_locale = :ja # デフォルトのlocaleを日本語(:ja)にする config.i18n.default_locale = :ja config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] その他、サービス公開までにやること(任意) 独自ドメイン取得 Google Analytics取得 Google Tag Manager取得 お問い合わせ用のGoogleフォーム作成(お題箱などでも代用可) 利用規約作成 プライバシーポリシー作成 エラー検知用にSentryを繋ぐ Herokuにデプロイする railsのバージョン違いでエラーが起こったら Heroku上でデータベースをつくる heroku rake db:migrate Herokuの無料枠でのスリープ回避 UptimeRobotを使用する(回避できてるのかな?) ほかにもあったら追記してみます。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

新規RailsプロジェクトをHerokuでデプロイするまでに最低限やることリスト10つ

はじめに RailsでアプリをつくってサクっとHerokuで公開するときに、とりあえずコピペでやっとくといいかもなリストです。 自分用の備忘録なので「あれもやったほうがいい!」とかはご容赦ください。 新しくRailsプロジェクトをつくる rails new <プロジェクト名> GitHubで履歴管理する 1. GitHubに新規リポジトリを作って接続 2. 空コミットする # リポジトリ作成 git init # 最初のコミット(空コミット) git commit --allow-empty -m "first commit" SQLiteからPostgresに変更 Rails6からコマンド1発ででいるようになったらしい。神。 #postgresqlに変更 rails db:system:change --to=postgresql # データベースをつくる createdb "dbname" # データベースの作成を完了させる rails db:create GemfileにGemを追加 自分がよく使うのはこんな感じ # for debug gem 'pry' # for design gem 'bootstrap' # use jQuery gem 'jquery-rails' gem 'jquery-turbolinks' # use font-awesome gem 'font-awesome-sass' # ogpの取得 gem 'open_uri_redirections' gem 'opengraph_parser' gem 'solargraph' # サイトマップを作る gem 'sitemap_generator' # sitemap自動更新用 gem 'whenever', require: false # 日本語対応 gem 'rails-i18n' # Slack通知(ユーザーからの投稿などがある場合は、Slack通知で不正なデータがないかチェック) gem 'slack-notifier' # Sentryでエラー検知 gem 'sentry-raven' # Kaminariでページング gem 'kaminari' bundle install jQueryを使えるようにする npm install --save jquery yarn install --check-files webpackをインストール rails webpacker:install サービスの根幹をつくる ・モデル作成 rails g model <モデル名> ・マイグレーションでカラム作成 rails g migration AddColumnTo<モデル名> rails db:migrate ・コントローラー作成 rails g controller <コントローラー名> ・ルーティング設定 config/routes.rb Rails.application.routes.draw do root 'results#index' # 存在しないページはトップページに飛ばす(これ最後に書かないとそこ以降は全部これに引っかかってとばされる…) get '*unmatched_route', to: 'results#index' end ・Viewのデザイン設定 集客、拡散させるためのコツ 画像の作成 ・Twitter用のカードをつくってassets/images配下に置く ・iPhoneでホーム画面に追加されるとき用のアイコン(apple-touch-icon.png)をつくってassets/images配下に置く ・faviconをつくってassets/images配下に置く ページのタイトル、説明、ogp画像を可変にする ・application helperで管理 app/views/layouts/application.html.erb <meta name="description" content="<%= page_description %>"> <meta property="og:title" content="<%= page_title %>"> <meta property="og:description" content="<%= page_description %>"> <meta property="og:url" content="<%= request.url %>"> <meta property="og:image" content="<%= page_image %>"> <meta name="twitter:card" content="summary_large_image"> <meta property="twitter:card" content="summary_large_image"> <meta name="twitter:image" content="<%= page_image %>"> app/helpers/application_helper.rb module ApplicationHelper def page_title title = "基本のタイトル" title = @page_title + " - " + title if @page_title title end def page_description description = "基本の説明" if @work description = "#{変数}と組み合わせたり" end description = @page_description.nil? ? description : @page_description end def page_image image = asset_url('基本のサムネイル')   # ページごとにサムネイルがあったら上書き if @works @works.each do |work| unless work&.thumbnail_url.blank? || work.nil? image = work&.thumbnail_url break end end end image end def get_twitter_card_info(page) twitter_card = {}   # ページごとにTwitterシェア時のサムネイルを変える if page twitter_card[:url] = page.url twitter_card[:title] = page.title twitter_card[:description] = page.description else twitter_card[:url] = '基本のURL' twitter_card[:title] = '基本のタイトル' twitter_card[:description] = '基本の説明' end twitter_card[:image] = asset_url('基本のサムネイル画像') twitter_card[:card] = 'summary_large_image' twitter_card[:site] = '@rubys8arks' twitter_card end end 日本にローカライズ エラーメッセージの日本語化 locals配下にja.ymlを置く タイムゾーンの日本時間化 config/application.rb # デフォルトのタイムゾーンを日本にする config.time_zone = 'Tokyo' config.active_record.default_timezone = :local config.i18n.default_locale = :ja # デフォルトのlocaleを日本語(:ja)にする config.i18n.default_locale = :ja config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] エラーが起きたときのページを日本語化 public配下の404.html、422.html、500.htmlの中身を変える その他、サービス公開までにやること(任意) 独自ドメイン取得 Google Analytics取得 Google Tag Manager取得 お問い合わせ用のGoogleフォーム作成(お題箱などでも代用可) 利用規約作成 プライバシーポリシー作成 エラー検知用にSentryを繋ぐ Herokuにデプロイする railsのバージョン違いでエラーが起こったら Heroku上でデータベースをつくる heroku rake db:migrate Herokuの無料枠でのスリープ回避 UptimeRobotを使用する(回避できてるのかな?) ほかにもあったら追記してみます。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ActiveRecordから任意のカラムだけ抜き出す【Ruby】【Rails】

忘れそうな(というか一度忘れた)のでメモ <Model> .<Query Interface> .pluck(:<Culumn1>, :<Culumn2>, ...) .map {|<Culumn1>, <Culumn2>, ...| {<Culumn1>: <Culumn1>, <Culumn1>: <Culumn2>, ...}} 例: User id name desc 1 a This is a 2 b This is b User .find(1) .pluck(:name, :desc) .map {|n, d| {name: n, desc: d}} #=> [{name: "a", desc: "This is a"}]
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

自分用RSpecリンク集

GitHub rspec/rspec-rails ドキュメント RSpec - Relish リファレンス(非公式) 使えるRSpec入門・その1「RSpecの基本的な構文や便利な機能を理解する」 - Qiita 使えるRSpec入門・その2「使用頻度の高いマッチャを使いこなす」 - Qiita 使えるRSpec入門・その3「ゼロからわかるモック(mock)を使ったテストの書き方」 - Qiita 使えるRSpec入門・その4「どんなブラウザ操作も自由自在!逆引きCapybara大辞典」 - Qiita パターン集 現場で使えるRSpecパターン集 for Rails App - mogulla3.tech スタイルガイド willnet/rspec-style-guide Better Specs 【初心者向け】レビュワーをイライラさせるRSpec集と解決方法 - メドピア開発者ブログ 亜流 rspecのrspecに学ぶ、ネストの深いrspecを書かない方法 - Qiita 俺のRSpecがこんなに雑なわけがない - Qiita サヨナラBetter Specs!? 雑で気楽なRSpecのススメ - Qiita 資料集リンク RSpecでテストを書くときの参考資料神7 - ナガモト の blog テスト用語 概念 TDD Red/Green/Refactor = 失敗/成功/リファクタリング テスト駆動開発 - Wikipedia BDD Given/When/Then = 状態/振舞/変化 GivenWhenThen - martinfowler.com AAA(Arrange/Act/Assert) = 準備/実行/検証 Arrange Act Assert - WikiWikiWeb 手法 E2E test = End to Endテスト 利用者によるブラウザ操作のテスト RSpec では System Spec に相当する。 Unit test = 単体テスト ソフトウェアの単体のモジュールのテスト(例: クラスやメソッドなど) RSpec では Model Spec などに相当する。 Integration test = 統合テスト 複数のモジュールのテスト(例: コントローラーのアクションやAPIなど) RSpec では Request Spec に相当する。 個人的なテストコードの方針 とりあえず System Spec 書いておけば無いよりはマシになる。 テストが重くなるので、System Spec から切り出せそうな処理はそれぞれの Spec として書いた方がいい。 API は Request Spec を書いて、関連付けやクラスなどが大きく複雑になってきたものに対しては Model Spec やら Form Spec , Service Spec などがあっても良いと思う。 ※ 要はこれが言いたかった↓
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

自分用RSpecリンク等まとめ集

GitHub rspec/rspec-rails ドキュメント RSpec - Relish リファレンス(非公式) 使えるRSpec入門・その1「RSpecの基本的な構文や便利な機能を理解する」 - Qiita 使えるRSpec入門・その2「使用頻度の高いマッチャを使いこなす」 - Qiita 使えるRSpec入門・その3「ゼロからわかるモック(mock)を使ったテストの書き方」 - Qiita 使えるRSpec入門・その4「どんなブラウザ操作も自由自在!逆引きCapybara大辞典」 - Qiita パターン集 現場で使えるRSpecパターン集 for Rails App - mogulla3.tech スタイルガイド willnet/rspec-style-guide Better Specs 【初心者向け】レビュワーをイライラさせるRSpec集と解決方法 - メドピア開発者ブログ 亜流 rspecのrspecに学ぶ、ネストの深いrspecを書かない方法 - Qiita 俺のRSpecがこんなに雑なわけがない - Qiita サヨナラBetter Specs!? 雑で気楽なRSpecのススメ - Qiita 資料集 RSpecでテストを書くときの参考資料神7 - ナガモト の blog テスト用語 概念 TDD Red/Green/Refactor = 失敗/成功/リファクタリング テスト駆動開発 - Wikipedia BDD Given/When/Then = 状態/振舞/変化 GivenWhenThen - martinfowler.com AAA(Arrange/Act/Assert) = 準備/実行/検証 Arrange Act Assert - WikiWikiWeb 手法 E2E test 利用者によるブラウザ操作のテスト RSpec では System Spec に相当する。 Integration test ソフトウェアの複数のモジュールのテスト(例: コントローラーのアクションやAPIなど) RSpec では Request Spec に相当する。 Unit test ソフトウェアの単体のモジュールのテスト(例: クラスやメソッドなど) RSpec では Model Spec などに相当する。 テストコードのないRailsアプリケーションにRSpecを導入する時の個人的方針 とりあえず System Spec 書いておけば無いよりはマシになる。 テストが重くなるので、System Spec から切り出せそうな処理はそれぞれの Spec として書いた方がいい。 API は Request Spec を書いて、関連付けやクラスなどが大きく複雑になってきたものに対しては Model Spec やら Form Spec , Service Spec などがあっても良いと思う。 ※ 要はこれが言いたかった↓
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

RSpec、書き始める前に知りたい集

GitHub rspec/rspec-rails ドキュメント RSpec - Relish リファレンス(非公式) 使えるRSpec入門・その1「RSpecの基本的な構文や便利な機能を理解する」 - Qiita 使えるRSpec入門・その2「使用頻度の高いマッチャを使いこなす」 - Qiita 使えるRSpec入門・その3「ゼロからわかるモック(mock)を使ったテストの書き方」 - Qiita 使えるRSpec入門・その4「どんなブラウザ操作も自由自在!逆引きCapybara大辞典」 - Qiita パターン集 現場で使えるRSpecパターン集 for Rails App - mogulla3.tech スタイルガイド willnet/rspec-style-guide Better Specs 【初心者向け】レビュワーをイライラさせるRSpec集と解決方法 - メドピア開発者ブログ 亜流 rspecのrspecに学ぶ、ネストの深いrspecを書かない方法 - Qiita 俺のRSpecがこんなに雑なわけがない - Qiita サヨナラBetter Specs!? 雑で気楽なRSpecのススメ - Qiita 資料集 RSpecでテストを書くときの参考資料神7 - ナガモト の blog テスト用語 概念 TDD Red/Green/Refactor = 失敗/成功/リファクタリング テスト駆動開発 - Wikipedia BDD Given/When/Then = 状態/振舞/変化 GivenWhenThen - martinfowler.com AAA(Arrange/Act/Assert) = 準備/実行/検証 Arrange Act Assert - WikiWikiWeb 手法 E2E test 利用者によるブラウザ操作のテスト RSpec では System Spec に相当する。 Integration test ソフトウェアの複数のモジュールのテスト(例: コントローラーのアクションやAPIなど) RSpec では Request Spec に相当する。 Unit test ソフトウェアの単体のモジュールのテスト(例: クラスやメソッドなど) RSpec では Model Spec などに相当する。 テストコードのないRailsアプリケーションにRSpecを導入する時の個人的方針 とりあえず System Spec 書いておけば無いよりはマシになる。 テストが重くなるので、System Spec から切り出せそうな処理はそれぞれの Spec として書いた方がいい。 API は Request Spec を書いて、関連付けやクラスなどが大きく複雑になってきたものに対しては Model Spec やら Form Spec , Service Spec などがあっても良いと思う。 ※ 要はこれが言いたかった↓
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

validates_uniqueness_ofとは

はじめに オリジナルアプリでいいね機能の実装に取り掛かっています。 そのとき初めて出てきた記述があったのでアウトプットしていきます。 validates_uniqueness_of いいね機能の実装のためにlikeモデルを作成しました。 like.rb class Like < ApplicationRecord #アソシエーション belongs_to :user belongs_to :review validates_uniqueness_of :review_id, scope: :user_id end userは1つの投稿に対して1つしかいいねをつけられないようにするためにバリデーションを記述しました。 validates_uniqueness_ofによって属性の値が一意であることをバリデーションが成立します。 validates :review_id, uniqueness: true しかしこのような記述では1つの投稿に対して1つしかいいねが押せないことになってしまいます。 そのためにscopeを使って、範囲を指定して、一意かどうかを判断します。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[エラー]こんなミスは嫌だ

はじめに 本記事では、これまでに学習した中で、 ヒューマンエラー、ケアレスミスをしてしまったことを紹介いたします。 私としても、同じことを繰り返さないために、備忘録としてここに記述します。 ケアレスミス resources 例 (正) resources :prototypes resources :prototypes do resources :comments, only: :create end resources :users, only: :show (誤) resources :prototypes resources :prototypes do resources :comments, only: :create resources :users, only: :show end usersまでネストしていたため、 Prefixも異なる事態に陥りました。 モデル (正)model (誤)medel 見つけた時は、笑いが止まりませんでした。 locals 以前の記事にも、載せましたが、 (誤)local (正)locals です。 img src (誤)img scr (正)img src eachメソッド 例 (正) <% @prototype.comments.each do |comment| %> (誤) <%= @prototype.comments.each do |comment| %> =をつけるととんでもないぐらいブラウザに情報が飛び交う。 何に=をつけるのか、つけないのか正確に理解する必要があります。 終了タグの抜け そのままの意味です。 アソシエーション (正) belongs_to :user has_one_attached :image has_many :comments , dependent: :destroy (誤) belong_to :user has_one_attached :image has_many :comment , dependent: :destroy 「s」抜け。見つけることは困難を極めます。 render (正) if prototype.save redirect_to prototype_path else render :edit end (誤) if prototype.save redirect_to prototype_path else render_to :edit end redirect_toに引っ張られないように。 7つのアクション new・・・新規投稿ページを表示 create・・・データの投稿を行う *逆にしない!! 終わり キリがないので、 これで終わりにします。 とにかくミスが発覚した時は、 例えケアレスだからと言って軽く扱わず、 間違えたことをアウトプットし、なぜ間違えたのかフィードバックを行うよう心がけましょう。 引き続き頑張ります!!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Rspec

初期設定 Rails で RSpecを利用する場合、一度だけ次のコマ ンドを実行する必要があります。 その結果、specディレクトリが作られて、その下に spec_helper.rb および rails_helper.rb というファイルが生成されます。 rails g rspec:install 使用方法 spec/models/_spec.rb require "rails_helper" RSpec.describe "User" do before do @user = build(:user) end it "すべての値が正しく入力されていれば登録できる" do expect(@user).to be_valid end it "nameがなければ登録できない" do @user.name = "" expect(@user).not_to be_valid end it "emailが存在しなければ登録できない" do user = build(:user, email: "") expect(user).not_to be_valid end it "emailが他のユーザーと重複したら登録できない" do user = build(:user, email: "test@test.com") tester = User.new(email: "test@test.com") expect(tester).not_to be_valid end it "password_digestが6文字以下の場合登録できない" do user = build(:user, password_digest: "cavaf") expect(user).not_to be_valid end end
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails]Capistranoで自動デプロイで気をつけたいこと

はじめに 前回、Capistranoによる自動デプロイを導入しましたが、その中で個人的に、コマンド一つ覚えていればいいかと勝手思っていましたが、自動デプロイする前にやるべきことがあります。 それを簡単に記事に残しておきます。 よろしくお願いします。 ローカルでVScodeを修正した場合 これは単純にアプリの改修や変更を行った場合、必ずリモートリポジトリにコミット、プッシュを行います。 もしブランチを切っている場合はmergeまで行います。 その後、一度プロセスをkillします。 例↓ まずはプロセスを確認します。 ターミナル [ec2-user@ip-172-31-23-189 <リポジトリ名>]$ ps aux | grep unicorn ec2-user 17877 0.4 18.1 588472 182840 ? Sl 01:55 0:02 unicorn_rails master -c config/unicorn.rb -E production -D ec2-user 17881 0.0 17.3 589088 175164 ? Sl 01:55 0:00 unicorn_rails worker[0] -c config/unicorn.rb -E production -D ec2-user 17911 0.0 0.2 110532 2180 pts/0 S+ 02:05 0:00 grep --color=auto unicorn 続いてプロセスをkill ターミナル # 上記の例だと「17877」 [ec2-user@ip-172-31-23-189 <リポジトリ名>]$ kill プロセス番号 そして最後にローカルのアプリディレクトリでbundle exec cap production deployを実行して完了。 ローカルでデータベース関連の内容を修正した場合 もしデータベース関連の修正を行った場合、まず本番環境で下記の二つのコマンドを実行します。 ※実行する際、「DISABLE_DATABASE_ENVIRONMENT_CHECK=1」というオプションが必要です。 ターミナル(本番環境) rails db:drop RAILS_ENV=production rails db:create RAILS_ENV=production その後、一度プロセスをkillします。 例↓ まずはプロセスを確認します。 ターミナル [ec2-user@ip-172-31-23-189 <リポジトリ名>]$ ps aux | grep unicorn ec2-user 17877 0.4 18.1 588472 182840 ? Sl 01:55 0:02 unicorn_rails master -c config/unicorn.rb -E production -D ec2-user 17881 0.0 17.3 589088 175164 ? Sl 01:55 0:00 unicorn_rails worker[0] -c config/unicorn.rb -E production -D ec2-user 17911 0.0 0.2 110532 2180 pts/0 S+ 02:05 0:00 grep --color=auto unicorn 続いてプロセスをkill ターミナル # 上記の例だと「17877」 [ec2-user@ip-172-31-23-189 <リポジトリ名>]$ kill プロセス番号 そして最後にローカルのアプリディレクトリでbundle exec cap production deployを実行して完了。 Nginxを修正した場合 Nginxの修正を行った場合は下記コマンドを実行します。  terminal:ターミナル sudo systemctl restart nginx 最後に Capistrano導入後、bundle exec cap production deployのコマンドさえ打てば自動デプロイしてくれると思っていましたが、もう一手間加えないといけなくて、私は少し失敗しました。 このような細かいところもしっかり身につけたいと感じました。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Rspecまとめ

すぐ忘れるので、まとめてみた Rspecを導入する Gemfile group :development, :test do gem "rspec-rails" end ターミナル rails g rspec:install .rspec # 見やすくするため追加 --format documentation FactoryBotを導入する Gemfile group :development, :test do gem "factory_bot_rails" end Capybaraを導入する Gemfile gem 'capybara' Rspecを実行する rails_helperの設定 spec/rails_helper require 'capybara/rspec' RSpec.configure do |config| config.include Devise::Test::IntegrationHelpers, type: :request #Deviseのテスト config.include FactoryBot::Syntax::Methods #FactoryBotの利用 end requrest_spec requestの導入 ターミナル # コマンドを打たずに、ファイルを手動で作成しても良い rails g rspec:request user top_spec.rb require 'rails_helper' RSpec.describe "Tops", type: :request do describe "GET /index" do before do get root_path end example "topページへアクセスできること" do expect(response).to have_http_status(:success) end example "ログイン機能が含まれること" do expect(response.body).to include("ログイン") end end end Deviseのspec users_controller.rb class UsersController < ApplicationController before_action :authenticate_user! def index @user = User.find(current_user.id) end end spec/factories/user.rb FactoryBot.define do factory :testuser, class: 'User' do name { "testuser" } sequence(:email) { |n| "testuser#{n}@user.com" } password { "foobar" } end end users_spec.rb require 'rails_helper' RSpec.describe "Users", type: :request do let(:user) { create(:testuser) } describe "GET /index" do context "ログインしていない場合" do example "ログインページへリダイレクトすること" do get users_path expect(response).to redirect_to user_session_path end end context "ログインしている場合" do before do sign_in user get users_path end example "indexページが表示できること" do expect(response).to have_http_status(:success) end example "ユーザー情報が含まれること" do expect(response.body).to include(user.name) expect(response.body).to include(user.email) end end end ransackのspec institutions_controller.rb class InstitutionsController < ApplicationController before_action :set_q def index max_num = 50 if @q.result.count > 50 @institution = @q.result.limit(max_num) else @institution = @q.result.all end end private def set_q @q = Institution.ransack(params[:q]) end end app/views/institution/index.html.erb <div class="institution_index_main"> <h3>医療機関検索フォーム</h1> <%= search_form_for @q, url: institutions_path do |f| %> <div class="flex_center"> <div class="search_form_container"> <div class="addres_cont_container"> <%= f.label :address_cont, '住所で検索' %> <%= f.search_field :address_cont %> </div> <div class="name_introduction_cont_container"> <%= f.label :name_or_introduction_cont, '情報で検索' %> <%= f.search_field :name_or_introduction_cont %> </div> </div> <div class="search_submit_container"> <%= f.submit '検 索', class:"search_submit", id: "institution_search_submit" %> </div> </div> <% end %> </div> factories/institution.rb FactoryBot.define do factory :testinstitution, class: "Institution" do name { "testinstitution" } postcode { 1234567 } address { "東京都東京区東京1-2-3東京ビル1F" } end end institution_spec.rb # request_specの場合 require 'rails_helper' RSpec.describe "Institutions", type: :request do let!(:institution) { create(:testinstitution) } describe "GET /index" do before do get institutions_path, params: { q: { name_cont: "test"} } end example "ページを表示できること" do expect(response).to have_http_status(:success) end example "医療機関情報が含まれること" do expect(response.body).to include(institution.name) expect(response.body).to include(institution.address) end end end spec/features/institution_feature_spec.rb # feature_specの場合 require 'rails_helper' RSpec.feature "Institution_Features", type: :feature do let!(:institution) { create(:testinstitution) } feature "医療機関検索" do before do visit institutions_path end scenario "住所に検索語を含むとき" do fill_in 'q[address_cont]', with: '東京都' find('#institution_search_submit').click expect(page.status_code).to eq(200) expect(page).to have_content(institution.name) expect(page).to have_content(institution.address) end scenario "住所に検索語を含まないとき" do fill_in 'q[address_cont]', with: '大阪府' find('#institution_search_submit').click expect(page.status_code).to eq(200) expect(page).not_to have_content(institution.name) expect(page).not_to have_content(institution.address) end scenario "検索欄が空欄のとき" do fill_in 'q[address_cont]', with: '' find('#institution_search_submit').click expect(page.status_code).to eq(200) expect(page).to have_content(institution.name) expect(page).to have_content(institution.address) end scenario "名前に検索語を含むとき" do fill_in 'q[name_or_introduction_cont]', with: 'test' find('#institution_search_submit').click expect(page.status_code).to eq(200) expect(page).to have_content(institution.name) expect(page).to have_content(institution.address) end scenario "名前に検索語を含まないとき" do fill_in 'q[name_or_introduction_cont]', with: 'example' find('#institution_search_submit').click expect(page.status_code).to eq(200) expect(page).not_to have_content(institution.name) expect(page).not_to have_content(institution.address) end scenario "検索欄が空欄の時" do fill_in 'q[name_or_introduction_cont]', with: '' find('#institution_search_submit').click expect(page.status_code).to eq(200) expect(page).to have_content(institution.name) expect(page).to have_content(institution.address) end end end ストロングパラメータのspec users_controller.rb class UsersController < ApplicationController before_action :authenticate_user! def update @user = User.find(current_user.id) if @user.update(user_params) redirect_to edit_user_path(current_user), notice: "プロフィール情報を更新しました" else render "edit" end end private def user_params params.require(:user).permit(:name, :image) end end requests/user_spec.rb require 'rails_helper' RSpec.describe "Users", type: :request do let(:user) { create(:testuser) } describe 'POST #create' do before do sign_in user end example 'リクエストが成功すること' do put user_path(user.id), params: { user: { name: "exampleuser", image: "image.png" } } expect(response.status).to eq 302 end example 'ユーザー名が更新されること' do expect do put user_path(user.id), params: { user: { name: "exampleuser", image: "image.png" } } end.to change { User.find(user.id).name }.from('testuser').to('exampleuser') end end end POST PUT DELETEメソッドのspec requests/institution_spec.rb require 'rails_helper' RSpec.describe "Institutions", type: :request do let!(:institution) { create(:testinstitution) } let(:param) do { institution: { name: 'examplehospital', postcode: 9876543, prefecture: "福岡県", address_city: "福岡市福岡", address_street: "4-5-6", address_building: "福岡ショッピング5F", address: "福岡県福岡市福岡4-5-6福岡ショッピング5F", introduction: "整形外科、リハビリテーション科", image: "examplehospital.png" } } end describe 'POST /create' do example 'リクエストが成功すること' do post institutions_path, params: param expect(response.status).to eq 302 end example '医療機関が登録されること' do expect do post institutions_path, params: param end.to change(Institution, :count).by(1) end end describe 'PUT /update' do example 'リクエストが成功すること' do put institution_path(institution.id), params: param expect(response.status).to eq 302 end example '医療機関情報が更新されること' do expect do put institution_path(institution.id), params: param end.to change { Institution.find(institution.id).name }.from('testinstitution').to('examplehospital') end end describe 'DELETE /destroy' do it 'リクエストが成功すること' do delete institution_path(institution.id), params: { id: institution.id } expect(response.status).to eq 302 end it '医療機関情報が削除されること' do expect do delete institution_path(institution.id), params: { id: institution.id } end.to change(Institution, :count).by(-1) end it '医療機関一覧にリダイレクトすること' do delete institution_path(institution.id), params: { id: institution.id } expect(response).to redirect_to(institutions_path) end end end feature_spec features_user_spec.rb require 'rails_helper' RSpec.feature 'Users_Features', type: :feature do include Devise::Test::IntegrationHelpers describe "user_login" do let(:user) { create(:testuser)} scenario "新規作成できるか" do visit new_user_registration_path expect(page).to have_content("新規登録") fill_in "user_registration_email", with: "example@example.com" fill_in "user_registration_password", with: "foobar" fill_in "user_registration_confirm_password", with: "foobar" expect do click_button "新規登録" end.to change(User, :count).by(1) end end describe "link_to_users" do let(:user) { create(:testuser) } background do sign_in user end scenario 'プロフィール画面からプロフィール編集画面へ遷移できるか' do visit users_path expect(page).to have_content(user.name) expect(page).to have_content(user.email) expect(page).to have_content("アカウント情報を編集する") expect(page).to have_content("プロフィールを編集する") click_link "プロフィールを編集する" expect(page).to have_content("ユーザープロフィール編集") end end end model/consultation.rb class Consultationhour < ApplicationRecord belongs_to :institution validates :start_time, presence: true, format: { with: /[[0-2]0-9]:[0-5][0-9]/, message: "は[00:00]の形式で入力してください" } validates :end_time, presence: true, format: { with: /[[0-2]0-9]:[0-5][0-9]/, message: "は[00:00]の形式で入力してください" } validate :before_start_time def before_start_time if start_time != nil && end_time != nil if end_time < start_time errors.add(:end_time, "は開始時間よりも後に設定してください") end end end end consultation_feature_spec.rb require 'rails_helper' RSpec.feature "Consultationhour_Features", type: :feature do let(:medicalstaff) { create(:teststaff) } let(:institution) { create(:testinstitution) } before do login_staff(medicalstaff) end feature "登録内容が正しいとき" do before do visit institution_path(institution.id) click_link "診療時間を登録する" end scenario "新規作成できるか" do fill_in "new_start_time", with: "08:00" fill_in "new_end_time", with: "13:00" find('.monday_container').all('option')[1].select_option find('.tuesday_container').all('option')[1].select_option find('.wednesday_container').all('option')[0].select_option find('.thursday_container').all('option')[1].select_option find('.friday_container').all('option')[1].select_option find('.saturday_container').all('option')[1].select_option find('.sunday_container').all('option')[2].select_option find('.holiday_container').all('option')[1].select_option fill_in "new_detail", with: "日曜日は非常勤医師" expect do click_button "登録する" end.to change(Consultationhour, :count).by(1) expect(page).to have_content("診療時間を追加しました") expect(page).to have_content("日曜日は非常勤医師") end end feature "登録内容が正しくないとき" do before do visit institution_path(institution.id) click_link "診療時間を登録する" end scenario "未入力エラーメッセージが表示されるか" do click_button "登録する" expect(page).to have_content("開始時間が入力されていません") expect(page).to have_content("開始時間は[00:00]の形式で入力してください") expect(page).to have_content("終了時間が入力されていません") expect(page).to have_content("終了時間は[00:00]の形式で入力してください") end scenario "開始時間と終了時間のエラーメッセージが表示されるか" do fill_in "new_start_time", with: "13:00" fill_in "new_end_time", with: "10:00" click_button "登録する" expect(page).to have_content("終了時間は開始時間よりも後に設定してください") end end end 中間テーブルのテスト spec/factories/favorite.rb FactoryBot.define do factory :testfavorite, class: "Favorite" do user { create(:testuser) } institution { create(:institution) } end end spec/features/user_feature_spec.rb describe "link_to_users" do let!(:user) { create(:testuser) } let!(:institution) { create(:testinstitution) } let!(:favorite) { create(:testfavorite, user: user, institution: institution) } background do sign_in user end scenario 'プロフィール画面からアカウント情報編集画面へ遷移し、プロフィール画面へ戻れるか', js: true do visit users_path expect(page).to have_content("お気に入り解除") find('.like-btn').click expect(page).not_to have_content("お気に入り解除") end 別)user作成時にfavoriteを作成する方法 spec/factories/user.rb FactoryBot.define do factory :testuser, class: 'User' do name { "testuser" } sequence(:email) { |n| "testuser#{n}@user.com" } password { "foobar" } after(:create) do |user| create(:testfavorite, user: user, institution: create(:testinstitution) ) end end end # traitを使う方法 FactoryBot.define do factory :testuser, class: 'User' do name { "testuser" } sequence(:email) { |n| "testuser#{n}@user.com" } password { "foobar" } trait :user_favorite do after(:create) do |user| create(:testfavorite, user: user, institution: create(:testinstitution) ) end end end end let(:user) { create(:testuser, :user_favorite) } # favoriteを作る let(:user) { create(:testuser) } # favoriteを作らない Javascriptのリンクをテスト spec/rails_helper.rb Capybara.javascript_driver = :selenium_chrome_headless # 追加 factories/institution.rb FactoryBot.define do factory :testinstitution, class: "Institution" do name { "testinstitution" } postcode { 1234567 } prefecture { "東京都" } address_city { "東京区東京" } address_street { "1-2-3" } address_building { "東京ビル1F" } address { "東京都東京区東京1-2-3東京ビル1F" } end end features/insitutiton_feature_spec.rb require 'rails_helper' RSpec.feature "Institution_Features", type: :feature do let!(:institution) { create(:testinstitution) } scenario "詳細ページへ遷移できるか", js: true do visit institutions_path find(".institution_index_tbody_tr").click expect(page).to have_content("医療機関情報") expect(page).to have_content("編 集") expect(page).to have_content("削 除") end scenario "医療機関情報を編集できるか" do visit edit_institution_path(institution.id) expect(page).to have_content("医療機関情報修正") fill_in "institution_name_text", with: "testclinic" click_button "更新する" expect(page).to have_content("testclinic") expect(page).not_to have_content(institution.name) end end ヘルパーを導入する spec/support/LoginMacro.rb module LoginMacro def login_staff(staff) visit new_medicalstaff_session_path fill_in 'medicalstaff_login_email', with: staff.email fill_in 'medicalstaff_login_password', with: staff.password click_on 'ログイン' end end spec/rails_helper.rb Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } # 有効化 RSpec.configure do |config| config.include LoginMacro # 追加 config.include Devise::Test::IntegrationHelpers, type: :request config.include FactoryBot::Syntax::Methods Capybara.javascript_driver = :selenium_chrome_headless end spec/features/institution_feature_spec.rb RSpec.feature "Institution_Features", type: :feature do let!(:institution) { create(:testinstitution) } feature "medicalstaffでログインしたとき" do let(:medicalstaff) { create(:teststaff) } before do login_staff(medicalstaff) end scenario "新規作成画面へ遷移できるか" do visit institutions_path expect(page).to have_content("医療機関検索フォーム") expect(page).to have_content(institution.name) click_link "新規作成" expect(page).to have_content("医療機関情報新規作成") end end end 参考資料 Rspecを導入する RSpecには表示の出力をキレイにする --format documentation というオプションがある FactoryBotを導入する 【Rails】RSpecとFactroyBotの導入・設定まとめ FactoryBotを使う時に覚えておきたい、たった5つのこと RSpec - FactoryBotを導入し、効率良く意味のあるデータを作成する Capybaraを導入する Capybaraチートシート Rspecを実行する 使えるRSpec入門・その1「RSpecの基本的な構文や便利な機能を理解する」 使えるRSpec入門・その2「使用頻度の高いマッチャを使いこなす」 Rspecでbindingを使って変数の中身を調べる方法 現場で使えるRSpecパターン集 for Rails App 今日から使える!RSpec 3で追加された8つの新機能 requrest_spec Rails RSpecの基本 ~Controller編~ Rails5でコントローラのテストをController specからRequest specに移行する Deviseのspec [Rails]Request Specでのログインの実施 RSpec初心者のdevise認証システムテスト Request SpecでDeviseのsing_in userを実施する ransackのspec ruby-on-rails - Rspecテストのランサックは常にすべてのインスタンスを返す 【Rails6】RSpecによる検索機能(ransack)の結合テストの実装 ストロングパラメータのspec Request Specでテストを書くときはStrong Parametersを通る前のパラメーターも意識しましょう POST PUT DELETEメソッドのspec Rails5でコントローラのテストをController specからRequest specに移行する feature_spec [Rails, devise, RSpec] テストでサインインする 使えるRSpec入門・その4「どんなブラウザ操作も自由自在!逆引きCapybara大辞典」 【RSpec/capybara】fill_inが上手く動作しない [Rails][RSpec] Capybaraでフォーム入力をシミュレートしてテストする 【Capybara】idもnameもlabelも存在しないセレクトボックスのオプションを選択する 中間テーブルのテスト rspecのテスト環境で多対多のアソシエーションを一括生成する方法 +α コントローラー単体テストエラーを解決したいです。 FactoryBotで中間テーブルのテストデータを用意する方法 Javascriptのリンクをテスト 【Rails】JavaScriptが絡むテスト ヘルパーを導入する サポートモジュールを使って結合テストの可読性を向上させる方法
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Rails】rails sのログに表示される「Cannot render console from <IPアドレス>!」とは何か?

はじめに dockerを使って、localhostで立ち上げたときに、rails server上で以下のようなログが発生。 web_1 |Cannot render console from 172.23.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1 結論 「docker のネットワークで使っているIPアドレス(172.23.0.1)がループバックの範囲(127.0.0.0~127.255.255.255)にないから、表示できないよ」 ↓ 「environment/development.rbに追記して、docker のネットワークで使っているIPアドレス(172.23.0.1)を許可しなければならないよ」 詳細 アウトラインはこちらの方の記事を参考に。 https://qiita.com/terufumi1122/items/73da039e6fc90ee0a63f ※補足「networks: 127.0.0.0/127.255.255.255」とは? 【ループバックアドレスの範囲】を指すようです。 ちなみに、「ループバックアドレス」とは自分自身を示す仮想的なIPアドレスです。 (例えば"localhost/3000" と "127.0.0.1/3000"はおおよそ等価と考えてよさそうです。) 「ループバックアドレスは一般的に127.0.0.1が指定されているけど、 状況次第で127.0.0.0~127.255.255.255の範囲で別のアドレスも設定できるよ」ということです。 詳しくは以下の記事で。 おわりに 簡単ですが、以上です。 どなたかの参考になれば幸いです。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MySQLに躓きすぎたので備忘録として残す

題名通り今回はMySQLで躓きすぎたので備忘録として、今後もしまた同じ目に遭ったとしても対処できるように備忘録として残す事にしました。 使用環境 Ubuntu : 18.04.3 LTS \n \l Rails : 6.1.3.2 MySQL : Ver 14.14 Distrib 5.7.34 Vagrant : 2.2.17 エラー内容 今回のエラーは、MySQLの環境構築の完了後マイグレーションしようとした時に出てきたエラーになっております。 結論 結論として、今回のエラーは「schema.rb」の環境がどうやら悪さをしていたみたいなので、今まで使用していた「schema.rb」を消して新しい「schema.rb」を作る事によって、無事MySQLのエラーをクリアすることができました。 エラー文の全容 マイグレーションしようとしたら出てきたエラー ターミナル $ rails db:migrate == 20200209055424 DeviseCreateUsers: migrating ================================ -- create_table(:users, {}) rails aborted! StandardError: An error has occurred, all later migrations canceled: you can't define an already defined column 'name'. /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:36:in `block in change' /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:5:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: ArgumentError: you can't define an already defined column 'name'. /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:36:in `block in change' /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:5:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:migrate (See full trace by running task with --trace) まず「devise_create_users」の36行目と5行目のカラム'name'が二つありますよというエラー文になります。 ということはカラム'name'を消せば解決です。 2 rails db:migrate:statusでマイグレーションの状態を確認する ターミナル $ rails db:migrate:status database: hoge_development Status Migration ID Migration Name -------------------------------------------------- up 20200208124233 Create hoges down 20200209055424 Devise create users down 20200220052712 Add hoges tosees down 20201207042223 Add hoge to hoges down 20201210015310 Add user id to hoges down 20201222045544 Create hoges down 20210303012038 Add hoge to users down 20210714052813 Create hoges 一応、rails db:migrate:statusで確認をしてからカラム'name'を消しました。 (statusがdownだと手動で直すことができます) 3.再びrails db:migrateをする ターミナル $ rails db:migrate == 20200209055424 DeviseCreateUsers: migrating ================================ -- create_table(:users, {}) -> 0.0673s -- add_index(:users, :email, {:unique=>true}) -> 0.0530s -- add_index(:users, :email, {:unique=>true}) rails aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Duplicate key name 'index_users_on_email' /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:41:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: ActiveRecord::StatementInvalid: Mysql2::Error: Duplicate key name 'index_users_on_email' /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:41:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Duplicate key name 'index_users_on_email' /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:41:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:migrate (See full trace by running task with --trace) 成功した!と思ったのも束の間、新たなエラーが、、、。 今度は、devise_create_users.rbの41行目とMySQLにエラー。。。 4.rails db:dropをしてみた devise_create_users.rbの41行目は直しても、MySQLかぁ。。。と思ったので、一度dropしてみました。 ターミナル $ rails db:drop rails aborted! ActiveRecord::NoEnvironmentInSchemaError: Environment data not found in the schema. To resolve this issue, run: bin/rails db:environment:set RAILS_ENV=development /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:drop => db:check_protected_environments (See full trace by running task with --trace) ※rails db:dropとは一度データベースを消すときに使います。 「bin/rails db:environment:set RAILS_ENV=development」というのが出ましたが、今はやめときました。 5.rails db:createしてみた ターミナル $ rails db:create Database 'hoge_development' already exists Database 'hoge_test' already exists 既に存在している模様 6.もう一度rails db:migrateしてみた ターミナル $ rails db:migrate == 20200209055424 DeviseCreateUsers: migrating ================================ -- create_table(:users, {}) rails aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Table 'users' already exists /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:5:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: ActiveRecord::StatementInvalid: Mysql2::Error: Table 'users' already exists /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:5:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Table 'users' already exists /vagrant/hoge/db/migrate/20200209055424_devise_create_users.rb:5:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:migrate (See full trace by running task with --trace) 若干変わったけど進展なし。。。 7.rails db:resetで実行 ターミナル $ rails db:reset rails aborted! ActiveRecord::NoEnvironmentInSchemaError: Environment data not found in the schema. To resolve this issue, run: bin/rails db:environment:set RAILS_ENV=development /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:reset => db:drop => db:check_protected_environments (See full trace by running task with --trace) 実行できない。。。(泣) おのれschemaめ。。。 8. bin/rails db:environment:set RAILS_ENV=development ターミナル $ bin/rails db:environment:set RAILS_ENV=development vagrant@ubuntu-bionic:/vagrant/hoge$ お!いけるか! 9.rails db:reset ターミナル $ bin/rails db:environment:set RAILS_ENV=development vagrant@ubuntu-bionic:/vagrant/hoge$ rails db:reset Dropped database 'hoge_development' Dropped database 'hoge_test' Created database 'hoge_development' Created database 'hoge_test' rails aborted! ActiveRecord::MismatchedForeignKey: Column `hoge_id` on table `hoges` does not match column `id` on `hoges`, which has type `bigint(20)`. To resolve this issue, change the type of the `hoge_id` column on `comments` to be :bigint. (For example `t.bigint :hoge_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/schema.rb:57:in `block in <top (required)>' /vagrant/hoge/db/schema.rb:13:in `<top (required)>' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/schema.rb:57:in `block in <top (required)>' /vagrant/hoge/db/schema.rb:13:in `<top (required)>' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:reset => db:setup => db:schema:load (See full trace by running task with --trace ...。 10. 念の為MySQLのバージョンを確認 ターミナル $ mysql --version mysql Ver 14.14 Distrib 5.7.34, for Linux (x86_64) using EditLine wrapper 11. rails db:migrate ターミナル $ rails db:migrate == 20200208124233 Createhoges: migrating ====================================== -- create_table(:hoges, {}) rails aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Table 'hoges' already exists /vagrant/hoge/db/migrate/20200208124233_create_hoges.rb:3:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: ActiveRecord::StatementInvalid: Mysql2::Error: Table 'hoges' already exists /vagrant/hoge/db/migrate/20200208124233_create_blogs.rb:3:in `change' /vagrant/hege/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Table 'blogs' already exists /vagrant/hoge/db/migrate/20200208124233_create_hoges.rb:3:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:migrate (See full trace by running task with --trace) エラーの内容が変わりました。 MySQLの何かが悪さをしています。 12. rails db:reset ターミナル $ rails db:reset Dropped database 'hoge_development' Dropped database 'hoge_test' Created database 'hoge_development' Created database 'hoge_test' rails aborted! ActiveRecord::MismatchedForeignKey: Column `hoge_id` on table `hoges` does not match column `id` on `hoges`, which has type `bigint(20)`. To resolve this issue, change the type of the `hoge_id` column on `hoges` to be :bigint. (For example `t.bigint :hoge_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/schema.rb:57:in `block in <top (required)>' /vagrant/hoge/db/schema.rb:13:in `<top (required)>' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/schema.rb:57:in `block in <top (required)>' /vagrant/hoge/db/schema.rb:13:in `<top (required)>' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:reset => db:setup => db:schema:load (See full trace by running task with --trace) どうやら一つはdatabase.ymlの入力がよろしくないようですね。 13.database.ymlを変更して再度rails db:reset ターミナル $ rails db:reset Dropped database 'hoge_development' Dropped database 'hoge_test' Created database 'hoge_development' Created database 'hoge_test' rails aborted! ActiveRecord::MismatchedForeignKey: Column `hoge_id` on table `hoges` does not match column `id` on `hoges`, which has type `bigint(20)`. To resolve this issue, change the type of the `hoge_id` column on `hoges` to be :bigint. (For example `t.bigint :hoge_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/schema.rb:57:in `block in <top (required)>' /vagrant/hoge/db/schema.rb:13:in `<top (required)>' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/schema.rb:57:in `block in <top (required)>' /vagrant/hoge/db/schema.rb:13:in `<top (required)>' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:reset => db:setup => db:schema:load (See full trace by running task with --trace) 変わらないな・・・。 最終手段でschemaを古いものを消して、新しくschemaを作る事にしました。 14. 一度まっさらな状態にして$ rails db:migrate:statusを見てみた ターミナル $ rails db:migrate:status Schema migrations table does not exist yet. 一応schemaファイルは無くなっていますね 15. schemaファイルを作り直してbin/rails db:migrate ターミナル $ bin/rails db:migrate == 20200208124233 Createhoges: migrating ====================================== -- create_table(:hoges, {}) -> 0.0566s == 20200208124233 Createhoges: migrated (0.0569s) ============================= == 20200209055424 DeviseCreateUsers: migrating ================================ -- create_table(:users, {}) -> 0.0592s -- add_index(:users, :email, {:unique=>true}) -> 0.0587s -- add_index(:users, :reset_password_token, {:unique=>true}) -> 0.0553s == 20200209055424 DeviseCreateUsers: migrated (0.1741s) ======================= == 20200220052712 AddBlogsTosees: migrating =================================== == 20200220052712 AddBlogsTosees: migrated (0.0000s) ========================== == 20201207042223 AddNameToBlogs: migrating =================================== -- add_column(:hoges, :name, :string) -> 0.1584s == 20201207042223 AddNameToHoges: migrated (0.1588s) ========================== == 20201210015310 AddUserIdToHoges: migrating ================================= -- add_column(:hoges, :user_id, :integer) -> 0.1395s == 20201210015310 AddUserIdToHoges: migrated (0.1397s) ======================== == 20201222045544 Createhoges: migrating =================================== -- create_table(:hoges, {}) rails aborted! StandardError: An error has occurred, all later migrations canceled: Column `hoge_id` on table `hoges` does not match column `id` on `hoges`, which has type `bigint(20)`. To resolve this issue, change the type of the `hoge_id` column on `hoges` to be :bigint. (For example `t.bigint :hoge_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /vagrant/onsen/db/migrate/20201222045544_create_hoges.rb:3:in `change' /vagrant/onsen/bin/rails:9:in `<top (required)>' /vagrant/onsen/bin/spring:15:in `<top (required)>' Caused by: ActiveRecord::MismatchedForeignKey: Column `hoge_id` on table `hoges` does not match column `id` on `hoges`, which has type `bigint(20)`. To resolve this issue, change the type of the `hoge_id` column on `hoges` to be :bigint. (For example `t.bigint :hoge_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/migrate/20201222045544_create_hoges.rb:3:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Caused by: Mysql2::Error: Cannot add foreign key constraint /vagrant/hoge/db/migrate/20201222045544_create_hoges.rb:3:in `change' /vagrant/hoge/bin/rails:9:in `<top (required)>' /vagrant/hoge/bin/spring:15:in `<top (required)>' Tasks: TOP => db:migrate (See full trace by running task with --trace) おしい・・・! どうやらhogesカラムのidをbigintに変えればいけそうな感じですね。 ※(t.bigint :hoge_id)に変えればよい 16.修正して再度bin/rails db:migrate ターミナル $ bin/rails db:migrate == 20201222045544 CreateHoges: migrating =================================== -- create_table(:hoges, {}) -> 0.0619s == 20201222045544 CreatHoges: migrated (0.0620s) ========================== == 20210303012038 AddProfileImageToUsers: migrating =========================== -- add_column(:users, :profile_image, :string) -> 0.1556s == 20210303012038 AddProfileImageToUsers: migrated (0.1557s) ================== == 20210714052813 CreateHoges: migrating ================================== -- create_table(:hoges) -> 0.0691s == 20210714052813 CreateHoges: migrated (0.0694s) ========================= 通った〜!! 疲れた。。。 MySQLは本当に面倒なので皆様も似たような現象がありましたら、「schema.rb」を見てみてください。 見てくださった皆様、お付き合いありがとうございました。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails]Bootstrapでヘッダーを整える

今回は、Bootstrapを使ってヘッダーにハンバーガーメニューの導入を行っていきます。 ヘッダーを指定した画面幅に応じて、コンテンツを表示したり、三本線の画像(ハンバーガーメニュー)を表示したりを切り替えていきます。 開発環境 ruby 2.6.3 Rails 5.2.6 Bootstrap 4.5 前提 前提として、Bootstrapの導入が行われている状態で説明していきます。 いきなり完成形 まずは、こんなことをして〜、の前にいきなり完成形のコードをのせておきます。 header <header class="sticky-top"> <nav class="navbar navbar-expand-md navbar-dark bg-dark text-white"> <a> <%= link_to 'Top', root_path, data: {"turbolinks" => false} %> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav ml-auto"> <% if user_signed_in? %> <li class="nav-item"> <%= link_to '投稿フォーム', new_post_path %> </li> <li class="nav-item"> <%= link_to '投稿一覧', posts_path %> </li> <li class="nav-item"> <%= link_to 'ランキング', ranks_rank_path %> </li> <li class="nav-item"> <%= link_to "ログアウト", destroy_user_session_path, method: :delete %> </li> <% else %> <li class="nav-item"> <%= link_to "新規登録", new_user_registration_path %> </li> <li class="nav-item"> <%= link_to "ログイン", new_user_session_path %> </li> <% end %> </ul> </div> </nav> </header> これだけで、あとはよろしく〜では、雑すぎるので、解説していきます。 ヘッダーを固定 header <header class="sticky-top"> : まず、ヘッダーを画面上部に固定します。 classにsticky-topをつけるだけで、上部に固定できます。(Bootstrap優秀〜) ブレークポイントの指定 header <!--ブレークポイントの指定--> <nav class="navbar navbar-expand-md"> : わかりにくいので、背景色、色の指定等の記述は削除しています。 navbar-expand-mdで、mdでナビゲーションバーとハンバーガーメニューの切り替えを行います。 ハンバーガーメニュー部分 ハンバーガーメニューアイコンの設置と開いたり閉じたりの処理を行っています。 header <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> : #navbarNavDropdownを対象に開閉を行っていきます。 「navbar-toggler」classが付与される要素にdata-toggle="collapse"、data-target="#[id名]"、aria-controls="[id名]"、aria-expanded="false"、aria-label="Toggle navigation" まとめ ハンバーガーメニューの実装がかんたんに実装できました。 Bootstrap日本語リファレンスにも説明がありますので、ぜひ調べてみてください。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Railsで架空のCafeのHPを作ってみよう!【14日目】『文字数が多い時のテストコード』編

概要 基本Railsの記法に則り書いていきます! 1から全ての説明ではなく その中であれ?どうやるの?と 疑問に思った点や実装に困った箇所を ピックアップして紹介していきます♩ 設定と準備 ・Rails ・HTML ・CSS ・Javascript(jQuery) ↑上記の言語とフレームワークを使い 架空(自分で考えたテキトーなもの)のCafeの HPを作っていこうと思います! 14日目の作業内容 ・単体テストコードの実行 14日目の気になった箇所 何百、何千字のある場合のテストコードはどのように 実行したらいいだろうか。 仮説 今まで自分が習ったテストコードの記述では spec/models/sample_spec.rb it 'textが10字以上だと追加できない' do @sample.text = "1234567890" @menu.valid? expect(@sample.errors.full_messages).to include('textは9文字以内で入力してください') end 一部抜粋して書いています。 このようにダブルクォーテーションで囲い文字列にして指定の文字数を入力していたが ここに何百時も何千時もい打ち込むのはめんどくさいし綺麗なコードとは言えない。 この文字列の部分を違う記述にすれば可能なはず。 結論 答えはとてもシンプルかつ簡単で spec/models/sample_spec.rb it 'textが100字以上だと追加できない' do @sample.text = "a" * 100 @menu.valid? expect(@sample.errors.full_messages).to include('textは99文字以内で入力してください') end このように1文字を100回反映させるように 演算子を使えば可能! 1000字でも10000字でも同じ記述で簡単にできる!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails]アプリケーション処理の基礎知識MVCとは

はじめに 以前習ったMVCについて改めて整理をする。 1.MVCとは モデル/ビュー/コントローラという役割の総称。webアプリケーションシステムの処理の構造を表している。 2.ルーティングとは クライアントから送られたリクエストを振り分ける。(リクエストの行先を指定する) *configディレクトリの「routes.rb」に記述します。 3.コントローラー(C)とは コントローラーは、MVCの役割の一つです。 リクエストに対応する処理を決めておき、ルーティングからリクエストを受け取って処理を行ったあと、クライアントにレスポンスを返します。 またレスポンスに必要となるデータがあれば、他の役割と連携してデータを所得したり受け渡しを行い、レスポンスを完成させます。 *コントローラ作成:rails g ファイルの種類 生成するファイル名 *基本的には指定する7つのアクションに処理が分類される ・index ・new ・create ・show ・edit ・update ・destroy 4.ビュー(V)とは ビューはMVCの役割の一つです。 ブラウザにレスポンスとして返す見た目を設定します。 ブラウザに表示できるのはHTMLファイルですが、Rubyを埋め込むことができるERB(テンプレートエンジン)を使用すれば、Rubyの記述を埋め込めます。 5.モデル(M)とは モデルはMVCの役割の一つです。 データーベースへのアクセスなど情報のやり取りに関する処理を担当しています。 モデルがあればベータベースにあるテーブルを管理できるようになります。 *モデル作成:rails g model モデル名 終わりに Webアプリケーションの基礎になるので、頭に叩き込みたいと思います。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

railsでfont awesomeの一部アイコンが表示されなかった原因

はじめに ポートフォリオのアイコンにfont-awesomeを使ってみたけど ブラウザによって表示されるアイコンと表示されないアイコンがあった。 chrome : 表示できない safari : 上手く表示される ネット記事で情報収集して解決法を試してみるも上手く行かなかったので 公式ページで表示アイコンの種類を触っていたら 上手くいったので、まとめておく。 使用技術 rails (6.1.4) ruby (2.7.3) font-awesomeの導入 下記記事を参考にして、font-awesomeを導入した。 gemはfont-awesome-railsではなく、font-awesome-sassは導入した方が 最新版のfont-awesomeを読み込みできるみたい。 ただし、使えないヘルパーメソッドもあるみたいなので 自分の使用用途に応じて選択が必要かも。 また、私の場合は上記だけでも上手く行かず scssファイルの変更も同時に必要だったので、下記記事も併せて参考にした。 原因 そもそもPro(有料版)で使用が保証されている アイコン(Beta版)を選択してしまっていた。 完全に公式ページを飛ばし読みしていた結果で自業自得。笑 でもBeta版のうち、一部アイコンは 上手く表示されたので、結局の所はよく分からない。 font-awesome画面 使用するアイコンを探せたら これをrailsのビュー(HTMLファイル)に貼り付ける。 サイズ変更 ちなみにfa-10xなどサイズ指定するクラスをiタグに命名すると、変更可能。 〇〇.html.erb <i class="fas fa-bookmark fa-10x"></I> なので、いまいちfont-awesome-sassで使えない ヘルパーメソッドがどういったものか理解できていない。 今のところ、自分の用途で困っていないので深追いはしないでおこう。 終わりに アイコンは使用する部分も多くなるので、少し慣れることができて良かった。 最後までお読み頂き、ありがとうございました。 以上。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Rails】pry-byebugを使ってdebugする方法

対象者 byebugを使ってデバックしたい方 目的 byebugを使ってアプリの状態を確認すること 実際の手順と実例 1.pry-byebugのインストール Gemfileに下記を追加 group :development do : : gem 'pry-byebug' end その後bundle installを実行します 2.使い方 rbファイルではbinding.pry erbファイルでは<% binding.pry %> 例としてブログの新規投稿を行うアプリを使います。 1.Controllerで使う場合 class BlogsController < ApplicationController : : def create blog = Blog.new(blog_params) binding.pry blog.save redirect_to blog_path(blog.id) end : : end 上記のようにsave前にbinding.pryをいれました。 このままサーバーを立ち上げてもロードされず、処理が一度止まります。 ここでTerminalに戻ると From: /home/ec2-user/environment/CARAVAN/app/controllers/blogs_controller.rb @ line 22 BlogsController#create: 18: def create 19: blog = Blog.new(blog_params) 20: blog.save     21: binding.pry =>22: redirect_to blog_path(blog) 23: end [1] pry(#<BlogsController>)> 21行目で処理が止まっているのが分かります。 コマンドで「blog」と入力すると、変数blogの内容が表示されます。 [1] pry(#<BlogsController>)> blog => #<Blog:0x00007f20ec1130f0 id: nil, title: "テストタイトル", category: "テストカテゴリー", body: "テスト本文", created_at: nil, updated_at: nil> [2] pry(#<BlogsController>)> 今回は何事もなく稼働しています。 例えば、ここで変数に何も入っていなければ(nil)、19行目に変数がうまく渡っていない、20行目でsaveがうまく行えていない等の可能性が考えられるので、エラー箇所がこのあたりにあると考えられます。 参照 Rails tutolial 7.1.3 debuggerメソッド 投稿者コメント エラー文が出ないときにpry-byebugにかなり助けられました! いまではアプリ作るときGemには必ず入れておきます My Profile プログラミング学習歴②ヶ月目のアカウントです! プログラミングスクールで学んだ内容や自分が躓いた箇所等のアウトプットの為に発信しています。 また、プログラミング初学者の方にわかりやすく、簡潔にまとめて情報共有できればと考えています。 もし、投稿した記事の中に誤り等ございましたら、コメント欄でご教授いただけると幸いです。 
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Rails]デプロイ後の修正を反映させる方法

はじめに 「AWSでデプロイしたはいいけど、デザインを修正したくなったよー」という人に向けた記事です。 デプロイ後の修正を反映させるには masterにpushする まずはローカル環境で修正したファイルをGitHubのmasterブランチにpushします。 $ git push origin master git cloneしたディレクトリにpullする EC2インスタンスが開始されていることを確認してから、sshコマンドで接続します。 $ ssh -i 秘密鍵.pem ec2-user@ipアドレス デプロイ時にgit cloneしたディレクトリに移動してpullします。 $ git pull origin master アセットをプリコンパイルする 修正がCSSなどの場合、アセットファイルをプリコンパイルする必要があります。 簡単にいうと、JavaScriptやCSSのアセットを通信量削減のためにギュッとまとめる仕組みです。 開発環境ではこの仕組みが自動で働いてましたが、 本番環境では行われないため手動で行います。 $ rails assets:precompile RAILS_ENV=production インスタンスを再起動して確認 EC2インスタンスを再起動し、きちんと反映されていればオッケーです。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

施設の営業時間を作成・登録する

モデルの作成 営業時間を作成、編集するためのモデルを作成 ターミナル rails g model Consultationhour start_time: time, end_time: time, monday: string, ... holiday: string, detail: string, instituion_id: integer rails db:migrate rails g controller Consultationhours create モデルの設定 institutionとconsultationhourは1対多の関係 consultationのバリデーションは正規表現で作成(こちらで正規表現の確認ができます) バリデーションを自作した場合は、validateにする必要があり models/institution.rb class Institution < ApplicationRecord has_many :consultationhours, dependent: :destroy end models/consultationhour.rb class Consultationhour < ApplicationRecord belongs_to :institution validates :start_time, presence: true, format: { with: /[[0-2]0-9]:[0-5][0-9]/, message: "は[00:00]の形式で入力してください" } validates :end_time, presence: true, format: { with: /[[0-2]0-9]:[0-5][0-9]/, message: "は[00:00]の形式で入力してください" } validate :before_start_time def before_start_time if start_time != nil && end_time != nil if end_time < start_time errors.add(:end_time, "は開始時間よりも後に設定してください") end end end end ルーティングの設定 institutionのidをconsultationhourに渡すため、memberを使用 config/routes.rb Rails.application.routes.draw do resources :institutions do member do get "consultationhour" end end resources :consultationhours end コントローラーの設定 institution#showに登録したconsultationhoursを一緒に表示 institution#consultationhourでconsultationhourを新規作成 renderはmodelを介さないため、必要なデータを一緒に渡す app/controllers/institution.rb class InstitutionsController < ApplicationController def show @institution = Institution.find(params[:id]) @consultationhours = @institution.consultationhours end def consultationhour @institution = Institution.find(params[:id]) @consultationhour = Consultationhour.new end end app/controllers/consultationhour.rb class ConsultationhoursController < ApplicationController def create @consultationhour = Consultationhour.new(consultationhour_params) institution_id = @consultationhour.institution_id if @consultationhour.save redirect_to institution_path(@consultationhour.institution_id), notice: "診療時間を追加しました" else @institution = Institution.find(institution_id) render template: "institutions/consultationhour" end end def edit @consultationhour = Consultationhour.find(params[:id]) end def update @consultationhour = Consultationhour.find(params[:id]) if @consultationhour.update(consultationhour_params) redirect_to institution_path(@consultationhour.institution_id), notice: "診療時間を更新しました" else @consultationhour.start_time = "00:00" if @consultationhour.start_time.nil? @consultationhour.end_time = "00:00" if @consultationhour.end_time.nil? render "edit" end end def destroy @consultationhour = Consultationhour.find(params[:id]) @consultationhour.destroy redirect_to institutions_path, notice: "診療時間を削除しました" end end private def consultationhour_params params.require(:consultationhour).permit(:start_time, :end_time, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday, :holiday, :detail, :institution_id) end Viewの設定 新規作成 hidden_fieldにinstitution.idを入れて、consultationhourにinstitution.idを渡す institutions/show.html.erb <div> <div> <h2>医療機関情報</h2> <div> <div>診療時間</div> <table> <tr> <th>時間</th> <th>月</th> <th>火</th> <th>水</th> <th>木</th> <th>金</th> <th>土</th> <th>日</th> <th>祝</th> <th>編集</th> <th>削除</th> </tr> <% if @consultationhours.exists? %> <% @consultationhours.each do |consultationhour| %> <tr> <td><%= consultationhour.start_time.to_s(:stamp) %> - <%= consultationhour.end_time.to_s(:stamp) %></td> <td><%= consultationhour.monday %></td> <td><%= consultationhour.tuesday %></td> <td><%= consultationhour.wednesday %></td> <td><%= consultationhour.thursday %></td> <td><%= consultationhour.friday %></td> <td><%= consultationhour.saturday %></td> <td><%= consultationhour.sunday %></td> <td><%= consultationhour.holiday %></td> <td><%= link_to "修正", edit_consultationhour_path(consultationhour.id) %></td> <td><%= link_to "削除", consultationhour, method: :delete, data: {confirm: "本当に削除しますか"} %></td> </tr> <% end %> <% else %> <div>診療時間が登録されていません</div> <% end %> </table> <div> <% if @consultationhours.exists? %> <% @consultationhours.each do |consultationhour| %> <%= consultationhour.detail %><br> <% end %> <% end %> </div> </div> <div><%= link_to "診療時間を登録する", consultationhour_institution_path(@institution.id) %></div> </div> </div> institutions/consultationhour.html.erb <div> <h2>診療時間作成</h2> <%= form_with model: @consultationhour do |f|%> <div> <%= f.label :start_time, "開始時間" %> <%= f.text_field :start_time %> </div> <div> <%= f.label :end_time, "終了時間"%> <%= f.text_field :end_time%> </div> <div> <div> <%= f.label :monday, "月曜日" %> <%= f.select :monday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :tuesday, "火曜日" %> <%= f.select :tuesday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :wednesday, "水曜日" %> <%= f.select :wednesday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :thursday, "木曜日" %> <%= f.select :thursday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :friday, "金曜日" %> <%= f.select :friday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :saturday, "土曜日" %> <%= f.select :saturday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :sunday, "日曜日" %> <%= f.select :sunday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :holiday, "祝日" %> <%= f.select :holiday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> </div> <div> <%= f.label :detail, "詳細" %> <%= f.text_area :detail %> </div> <%= f.hidden_field :institution_id, value: @institution.id %> <div> <%= f.submit "登録する" %> </div> <% end %> <div> <%= link_to "医療機関情報へ戻る", institution_path(@institution.id) %> </div> </div> 編集する consultationhours/edit.html.erb <div> <h2>診療時間編集</h2> <%= form_with model: @consultationhour do |f|%> <div> <%= f.label :start_time, "開始時間" %> <%= f.text_field :start_time, value: @consultationhour.start_time.to_s(:stamp) %> </div> <div> <%= f.label :end_time, "終了時間"%> <%= f.text_field :end_time, value: @consultationhour.end_time.to_s(:stamp) %> </div> <div> <div> <%= f.label :monday, "月曜日" %> <%= f.select :monday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :tuesday, "火曜日" %> <%= f.select :tuesday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :wednesday, "水曜日" %> <%= f.select :wednesday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :thursday, "木曜日" %> <%= f.select :thursday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :friday, "金曜日" %> <%= f.select :friday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :saturday, "土曜日" %> <%= f.select :saturday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :sunday, "日曜日" %> <%= f.select :sunday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> <div> <%= f.label :holiday, "祝日" %> <%= f.select :holiday, [["-", "-"], ["●", "●"], ["※", "※"]] %> </div> </div> <div> <%= f.label :detail, "詳細" %> <%= f.text_area :detail %> </div> <div> <%= f.submit "更新する" %> </div> <% end %> <div> <%= link_to "医療機関情報へ戻る", institution_path(@institution.id) %> </div> </div> 日本時間に合わせる・時間の表示を設定する config/application.rb module SearchMedical class Application < Rails::Application config.time_zone = "Tokyo" end end confing/initializers/time_formats.rb Time::DATE_FORMATS[:stamp] = "%H:%M" エラーメッセージを表示する app/views/shared/_error.html.erb <% if obj.errors.any? %> <% obj.errors.full_messages.each do |message| %> <ul> <li><%= message %></li> </ul> <% end %> <% end %> app/views/consultationhour/edit.html.erb <%= render "shared/error", obj: @consultationhour %> エラーメッセージを日本語化する config/application.rb config.i18n.default_locale= :ja config/locals/ja.yml ja: activerecord: attributes: consultationhour: start_time: "開始時間" end_time: "終了時間" 参考記事 Railsのルーティングをカスタマイズしたときのメモ [Rails] dependent: :destroy について Railsのrenderの書き方多すぎ問題について 別のコントローラをrenderする方法 Rails: ビューでstrftimeを直書きするのはたぶんよくない(翻訳) 【Rails】 Railsのバリデーションの使い方をマスターしよう! 簡単! Railsで過去の日付に対するバリデーションを設定してみた Rails エラーメッセージの表示と日本語化
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Rails6でjQueryを使おうとしたらハマった

Rails6.0.3にjQueryを入れようとしたら5日間ハマった話 by @tatsuhiko-nakayama様 こちらの記事で yarn add jquery config/webpack/environment.js const { environment } = require('@rails/webpacker') // 以下追記 const webpack = require('webpack') environment.plugins.prepend('Provide', new webpack.ProvidePlugin({ $: 'jquery/src/jquery', jQuery: 'jquery/src/jquery' }) ) // ここまで module.exports = environment config/webpack/environment.js const { environment } = require('@rails/webpacker') // 以下追記 const webpack = require('webpack') environment.plugins.prepend('Provide', new webpack.ProvidePlugin({ $: 'jquery/src/jquery', jQuery: 'jquery/src/jquery' }) ) // ここまで module.exports = environment config/javascript/packs/application.js //中略 require("@rails/ujs").start() require("turbolinks").start() require("@rails/activestorage").start() require("channels") // 追記 require('jquery') //中略 をやったのだが下のエラー発生 ERROR in ./app/javascript/packs/application.js Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Cannot find module './node_modules/@rails/webpacker/package/babel/preset.js' from '/myapp' webpackのインストールが失敗? いや、node_modulesとbabelって書いてあるからそこが不足しているのか… など色々試行錯誤したが、 結局アンインストールして入れ直しで解決 # webpacker:installで追加されたpackage.jsonから無効なbabelpresetを削除 yarn remove @rails/webpacker yarn remove webpack webpack-cli webpack-dev-server rm -fr node_modules rm -fr public/packs bundle exec rails webpacker:install Railsアプリの階層にある.browserlistrcを手動で削除する yarn add node-releases yarn add electron-to-chromium bundle exec rails webpacker:compile # おわり 備考 Rails6のwebpackerは壊れやすいようです。 npmも同じく壊れやすいらしいので色々インストールしてる間に、コンフリクトしたのかなと分析。 解決まで時間がかかり焦ってしまったが、明けない夜はないように明けないエラーもないのかなと。 参考
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む