- 1. モデルの作成とマイグレーション
- 2. RSpecでApplicationHelperのメソッドを使いたいとき
- 3. Rubyの配列・ブロックの基礎についてまとめてみた。
- 4. 【RSpec】sleepは使うな
- 5. 異なるdocker-composeのMySQLコンテナのデータをRailsに流し込む
- 6. 【Mac】rbenvがインストールできないときの解決方法
- 7. フレームワークについて知ろう!
- 8. 【Ridgepole】カラムを指定して外部キーを加える
- 9. has_many, has_many through など関連付けについてのメモ
- 10. Bootstrapとfont-awesomeをRailsにインストールするやり方 Githubを参考に
- 11. 【Rails】hamlで画像を呼び出す
- 12. Rails form_with 解説してみる
- 13. 【rails】RSpecによる単体テスト
- 14. enumをセレクトボックスで扱う方法
- 15. provideメソッド
- 16. TECH CAMP 5週目
- 17. 【Rails】アソシエーション 違う名前で呼び出す
- 18. Rails 6 の pararell test がうまく行っていない皆様へ
- 19. いきなりの躓き rails 環境について
- 20. 【Rspec】Devise::MissingWardenエラーの解決策
モデルの作成とマイグレーション
#モデル作成の流れ
ここではTaskモデルを作成する流れを示します。
はじめに以下のコードを入力します。“`
#フレームワーク
$ bin/rails g model [モデル名] [属性名:データ型] [属性名:データ型] …$ bin/rails g model Task name:string description:text
“`
これで以下のファイルが生成されます。
・モデルクラスのソースコード(task.rb)
・マイグレーションファイル(2020~_create_task.rb)
・モデルの自動テスト(task_test.rb)
・モデルの自動テストで使うfixtureファイル(tasks.yml)ここでマイグレーションファイルとは、データベース構造への変更が示されたファイルのこと。
マイグレーションファイルの中身は以下の通りになっています。“`2020~_create_task.rb
class CreateTasks < ActiverecordMigration[5.2] def change create_table :t
RSpecでApplicationHelperのメソッドを使いたいとき
テストファイルでも、ヘルパーメソッドを使いたいときってありますよね。
`ApplicationHelper`を使いたい場合を想定します。
## 複数のファイルで利用したいとき
`spec/rails_helper.rb`で`ApplicationHelper`を`include`すればよいです。“`spec/rails_helper.rb
include ApplicationHelper
“``spec`ファイルは基本的にどれもトップレベルで`require rails_helper`しているはずなので、`spec/rails_helper.rb`で`include`してあげっちゃえばよいわけです。
## 1つのファイルでのみ利用したいとき
対象のテストファイルで`ApplicationHelper`を`include`すればよいです。
例にSystemSpecを挙げます。“`spec/systems/sample_spec.rb
include ApplicationHelper
“`## もし`include`を忘れたら
もし`include`を忘れ
Rubyの配列・ブロックの基礎についてまとめてみた。
#配列の特徴
●インデックス指定で要素を取り出す“`sample.rb
n = [1, 2, 3]
n[1] #=>2
“`●どんなオブジェクトも混在して入れる事ができる。
“`
s = [‘osaka’, 1, :hello]
“`●存在しない要素を指定するとnilが返ってくる
“`sample.rb
n = [10, 20 ,30]
n[3] #=>nil
“`●<<で配列の最後に要素を追加できる ```sample.rb food = ["apple", "peech"] food << "natto" food #=>[“apple”, “peech”, “natto”]
“`#ブロックについて
>メソッド呼び出しの際に引数と一緒に渡すことのできる処理のかたまり | たのしいRuby例えばこんなものです。
“`sample.rb
words = [‘a’,’p’,’p’,’l’,’e’]
food = “” #カラの文字列words.each do |w|
food += w
endputs food
#=>app
【RSpec】sleepは使うな
## 発生した問題
`Cancel my account`ボタンをクリックすると`Are you sure?`という確認のポップアップが表示され、
「OK」を押すとユーザーが削除される、といった(ごく普通の)ユーザー削除機能のテストを書きました。“`ruby
describe ‘ユーザー削除’, js: true do
it ‘ユーザーが削除されること’ do
expect(User.count).to eq(1)click_button ‘Cancel my account’
page.accept_confirm ‘Are you sure?’expect(User.count).to eq(0)
end
end
“`結果、失敗(; ・`ω・´)
“`zsh
Failures:1) Users::RegistrationsController ユーザー削除 ユーザーが削除されること
Failure/Error: expect(User.count).to eq(0)
異なるdocker-composeのMySQLコンテナのデータをRailsに流し込む
レアケースなのであまり参考にならないかもしれませんが、将来の私に何か役に立つことがあるかもしれないので、念の為残しておく備忘録です。
# 背景
関係のない2つのMySQLコンテナが存在している。
片方は非RailsのMySQLデータベース、片方はRailsのマイグレーションで作られたMySQLデータベース。
いずれも別々のdocker-compose環境で動作している。今回は非RailsのデータをRailsのデータベースに流し込む需要があって、
割とサクッと実現できたので、環境の設定や手法を以下に記します。# docker-compose.yml
行頭に `+` がついている行が、今回の作業のために追加した設定です。
別々のdocker-compose環境を同一networkで繋ぐために設定を追加します。## 非Rails環境
“`diff:docker-compose.yml
version: ‘2’
services:
mysql:
container_name: mysql
image: mysql:5.7.21
po
【Mac】rbenvがインストールできないときの解決方法
#エラー内容の確認
下記のようなエラー内容になったことでrbenvがインストールできないときのエラーの解消方法についてご紹介します。“`
$ brew install rbenv
The program ‘brew’ is currently not installed. To run ‘brew’ please ask your administrator to install the package ‘linuxbrew-wrapper’
“`### Linuxbrewのインストール
エラーの記述内容にLinuxbrewをインストールしてくださいとありますので下記のコマンドを実行します。“`
$ sh -c “$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/install/master/install.sh)”
“`
するとまたエラー内容が表示されてしまいました!“`
Warning: /home/linuxbrew/.linuxbrew/bin is not in your PATH.
フレームワークについて知ろう!
##フレームワークとは?
そもそもフレームワークとはなんなのでしょうか?
簡単にいうと枠組みのことです。Webアプリケーションを作成する際に、フレームワークでアプリケーションの雛形を作成します。webアプリケーション開発に必要なファイルを自動で作ってくれるので、それらを編集することで、効率的にwebアプリケーション開発ができます。
##フレームワークの種類
フレームワークはWebアプリケーション開発で用いられる各プログラミング言語ごとに存在します。Ruby | Ruby on Rails、Sinatra
PHP | Laravel、CakePHP
Java | Spring Framework、Java EEなどがあります。
フレームワークを使うことで簡単にアプリを作ることができるので活用してみてはいかがでしょうか。
最後までご覧いただきありがとうございます。
【Ridgepole】カラムを指定して外部キーを加える
こんにちは。Webエンジニアのインターンを始めて早くも20日が経ちそうな見習いプログラマです。
仕事はまだチュートリアルを行なっている段階なのですが、現場のレベルが高いので本格的な業務に参画するのが楽しみですね!
# What
RailsによるWebアプリケーション開発において、データベースのスキーマを管理する際に**ridgepole**を使うことがあると思います。この記事では、ridgepoleでスキーマを管理する際に、”**外部キー制約を加えるにはどうしたら良いか**”を簡単にまとめます。
また、外部キー制約をつける際、”**カラムを指定して外部キーを加えるにはどうしたら良いか**”そして”**どんな場合にカラムを指定して制約を加える必要があるのか**”についても並行して簡単にまとめます。
# Why
現在Rails開発のチュートリアルを行なっており、その一環としてTwitterのようなページを作成しています。しかし、ridgepoleの外部キー制約に関する記事や情報が少なく苦戦した箇所がいくつかありました。
特にModelで、has_many: through
has_many, has_many through など関連付けについてのメモ
関連付けに関してごっちゃになりそうなのでメモ。
間違い箇所などありましたらご指摘お願いします。
# has_many
例えばあるユーザー(User)が複数のタスク(Task)を持っていて、それを関連付ける場合などで用いるメソッド。“`user.rb
class User < ApplicationRecord has_many :tasks end ``` この場合は、 ユーザーがタスクモデルを見つけ出し、デフォルトでこのクラス(ここではUser)の名前 + \_id のと定義されているカラムを外部キーとみなす。 つまりここでは、UserがTaskを見つけ出し、そのTaskのuser\_idカラムを外部キーとして扱うことにより、関連づく。 当たり前だが、UserのidとTaskのuser\_idが関連づくことになる。 Taskにuser\_idが存在しなければ外部キーを他のカラムに指定しない限り、関連づけることができない。 Taskインスタンスを作成するときに、外部キーにUserのidを入れる必要があるが、その場合は ``` # userに何らかのインスタンスが
Bootstrapとfont-awesomeをRailsにインストールするやり方 Githubを参考に
# はじめに
Railsにデザインを整えるBootstrapとアイコンを使えるようになるfont-awesomeのgemを導入する方法を紹介します。それぞれのgemのGithabのページを参考にしました。
#Bootstrapの導入方法
まずGemfileにgemを追加します。“`ruby:
gem ‘bootstrap’, ‘~> 4.4.1’
“`
`sprockets-rails gem` がv2.3.2以上であることを確認しておいてください。
次に、`bundle insall`を実行して、サーバーを再起動します。次はマニフェストファイルである`app/assets/stylesheets/application.scss`に読み込ませます。拡張子が.scssになっているか確認しとく。
“`application.scss
@import “bootstrap”;
“`Bootstrap JavaScriptはJQueryに依存しているので、Rails 5.1以上を利用している場合は、`jquery-rails` gem をGemfileに加える必要があり
【Rails】hamlで画像を呼び出す
#背景
hamlで画像を呼び出すことを自分用のメモとして残す。#手順
1:app/assets/images/ に対象画像を置く。 例) app/assets/images/test.png
2:呼び出し“`test.html.haml
= image_tag ‘test.png’, class: ”, heigth: ”, weigth: ”“`
Rails form_with 解説してみる
どうもチャンクノです。
今回は前回の記事で書いたform_withの解説をしてみようかなと思います。
間違ってる部分ありましたら修正するのでコメントにて伝えてください。はい、では以下のコードをご覧ください。
“`
<%= form_with model: [:user, current_user], url: user_user_profile_path, local: true do |f| %>
<%= f.fields_for :user_profile, current_user.user_profile || current_user.build_user_profile do |profile| %>
<%= profile.text_field :name %>
<% end %>
<%= f.fields_for :user_address, current_user.user_address || current_user.build_user_address do |address| %>
<%= address.text_fie
【rails】RSpecによる単体テスト
Rspecを用いることでアプリケーションの単体の機能をテストすることができる。
### テスト対象のバリデーション
以下では、モデルに記載されたバリデーションの動作テストを例として扱う。
次のとおり、userモデルにバリデーションが記載されていて、データ保存時に次の条件をチェックしている。
・nicknameカラムの値が入っていること
・nicknameカラムの値の長さが、最大6文字であること
・emailカラムの値が入っていること“`rails:app/models/user.rb
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :remembera
enumをセレクトボックスで扱う方法
# 背景
enumの値をセレクトボックスで使いたくて調べていたが、どれも難しく書いてあり分かりにくかったので自分なりにまとめてみました!## enumとは
こちらの記事を参照ください!
https://qiita.com/ren0826jam/items/2870486578dc530c7074##手順
1.マイグレーションファイルを作成する。
※今回はProductモデルの以下のカラムのデータをenumを活用して保存します。“`20××××××××××.rb
class CreateProducts < ActiveRecord::Migration[5.2] def change create_table :products do |t| 省略 t.integer :status, null: false t.integer :bear, null: false t.integer :days, null: false 省略 end end end ``` 2.enumの設定を記述する。 ```model
provideメソッド
#provideメソッド
“`
<% provide(:title, "Home") %>
パラメータの引き渡し(定義みたいな感じ)
“`
“`
<%= yield(:title) %> | Ruby on Rails Tutorial Sample App
<%= yield(:title) %> ← Homeが入る
“`
連想配列のキーと値みたいなもんかな??
TECH CAMP 5週目
Chat-spaceの実装が一段落し、次はそのデプロイに向けて学習を行いました。そして課題は完了。いよいよ自分だけの力でアプリケーションを作る時がきました。
【学習内容】
・サーバーの基礎知識
・AWS
・個人アプリ制作実は私、前職は工場で働いていました。実際に製品を作るラインに約12年、管理者になって約1年、そして別の工場に出向になってそこで管理職として3年。出向先の工場では主に課長職とTCD(Total cost down)担当、QCC(Quality control circle)教育担当に従事し、原価低減活動、品質向上活動の取りまとめや社員教育を行なってきました。
よく「生産性」という言葉を耳にしますが、工場なんかではかなりシビアに数値でのやり取りが行われます。作業における社員の歩く秒数さえもストップウォッチで計測し、その時間を1秒でも縮めようと努力します。そしてその積み重ねが例えば残業時間30時間/月が0時間/月になったりと、会社にとって大きな利益へと繋がっていきます。それは”急いで作業をやれ”ではなく仕組みや手順の観点から改善を行います。
なので、「生産性」という言葉
【Rails】アソシエーション 違う名前で呼び出す
##目的
アソシエーションを利用して、違う名前で呼び出した方がわかりやすい
けど、どう書いたらいいかわからない
そんな時のオプション、class_nameについてまとめます。## class_nameオプション
関連を設定するモデルクラス名を指定利用場面としては、関連名と参照先のクラス名を変えたい時に使う
“`ruby:model/event.rb
class Event < ActiveRecord::Base belongs_to :user has_many :comments end ``` 上記はイベントがユーザーに属するぞと 書いてあります。 したがって @event.user という感じで、ユーザーをメソッドで呼び出すことができるのですが .userをここはオーナーと書いた方が意味が通じやすい、というケースは下記のように書き換えられます。 ```ruby:model/event.rb class Event < ActiveRecord::Base belongs_to :owner, class_name: 'User' has_m
Rails 6 の pararell test がうまく行っていない皆様へ
# はじめに
Rails 6 でパラレルテストをやりたいけど、なんかうまくいかない、という方が読んでいただけたら参考になるかもしれないことを書いていこうと思います。# やったこと
Headless Chrome なんかを使うシステムテストでは `PARALLEL_WORKERS=1` とすることで、並列でテストを動かすことを諦めましょう。それ以外のテストはお持ちの機材に合わせて `PARALLEL_WORKERS=$(grep processor /proc/cpuinfo | wc -l)` とでもしとけば動いてくれると思います。コードは [Github](https://github.com/seahal/qiita) にもあるので「エスパーかよ…」という方は、そっちも見ていだければと思います。# おわりに
あんまり理解してないで、やってみたらうまくいきました。ちゃんと動く理由とか根拠とかは聞かないでください…# 編集履歴
1. Github Actions で落ちていたので、なかったことにしてください…
2. Github Actions で動くようになり
いきなりの躓き rails 環境について
progateで勉強を始めました。progateにそって環境構築を進めていましたが
rails sとする際にrequired)>’
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/sqlite3-1.3.13-x64-mingw32/lib/sqlite3.rb:6:in `require’: cannot load such file — sqlite3/sqlite3_native (LoadError)と出て先に進めません。sqlite3がうまくDL出来ていないのでしょうか?
どなたかご教授いただけないでしょうか?
windows10使用です
【Rspec】Devise::MissingWardenエラーの解決策
##状況
Rspecのコントローラースペックを実装中に表題のエラーが発生しました。
初めて見るエラー文で戸惑ったのですが、解決策がシンプルだったため記載します。##環境
railsを用いたアプリ開発中で、deviseを用いたユーザー登録機能を実装している。##解決策
結論から。
エラー文には“`
Make sure that your application is loading Devise
and Warden as expected and that the `Warden::Manager`
middleware is present in your middleware stack.
If you