TECH EXPERT 24日目

TECH::EXPERT

メンターさんの好意で質問会なるものを開いていただいた。
少人数で質問できるので有意義な反面、他人の質問に時間を取られるので効率は悪い。1時間半の長丁場であったが、大きく得たものがあったかというと疑問。
個人的にはチャットの質問で十分かな。必要に応じてフォンティスで直にメンターさんを捕まえた方が早い。

devise

users controllerはrails g controller usersで作るのが正しいのか?

Rails

cssを読み込む順

@importの上から順。
reset cssを最初に書く。

Ynaqdh

rails gでconflictした際にでる。

Y - yes, overwrite
n - no, do not overwrite
a - all, overwrite this and all others
q - quit, abort
d - diff, show the differences between the old and the new
h - help, show this help
m - merge, run merge tool

フラッシュメッセージ

flash[:hoge]という使い方だと、表示する該当ページとその次のページでも出力される。つまり次のアクションまでがメッセージの寿命。
1回だけ表示にする場合にはflash.nowとする。
逆に表示し続けたい場合にはflash.keepとする。

devise経由の場合はデフォルトが英語メッセージとなっているため、以下の通り日本語化する。

日本語化

下記のサイトから日本語ファイルをダウンロードしてconfig/locales以下に配置
– devise.ja.yml
– ja.yml

config/application.rbに以下を追記

module Project名
  class Application < Rails::Application
    #〜省略〜
    config.i18n.default_locale = :ja
  end
end

deviseでの使い方

hamlだと以下のように書く。

.notification
  - flash.each do |key, value|
    = content_tag :div, value, class: key

flashの内容がnotificationとalertのハッシュのため、eachで出力する。

tableへのindexの貼り方

最初にモデルを作った時にmigrationファイル内へ直接書く。

class CreateGroups < ActiveRecord::Migration[5.0]
  def change
    create_table :groups do |t|
      t.string :name, null: false
      t.index :name, unique: true
      t.timestamps
    end
  end
end

もしくはadd to でindexを後から貼る。

カラムの足し引きとリファレンス

足す場合

rails g migration AddColumnToTable

migrationファイルを作成して、以下を書き込む

class AddIntroductionToMembers < ActiveRecord::Migration[5.0]
  def change
    add_reference :members, :user, foreign_key: true
    add_reference :members, :group, foreign_key: true
  end
end

rails db:migrateして終了

引く場合

 rails g migration RemoveUser_idFromMembers

Remove_Fromでmigrationファイルを作成。

def change
  remove_column :users, :name
end

リファレンス

integerではなく、references型と宣言する。
その上でforeign_key: trueにする。

Add_Columnのときはreferenceと単数形

class AddIntroductionToMembers < ActiveRecord::Migration[5.0]
  def change
    add_reference :members, :user, foreign_key: true
    add_reference :members, :group, foreign_key: true
  end
end

新規にmigrationファイルに書き込んで定義する時は複数形
こんなん分かるわけないだろ。
ちなみにわざわざuser_idと書く必要はなく、テーブル名の記載にすれば、自動的にuser_idのカラムが作成される。

t.references :user, foreign_key: true

外部キーに設定すると、データベース場ではMUL(multiple key)という名称になる。

Railsの外部キー制約とreference型について - Qiita
株式会社TECHLUCKという会社で代表兼エンジニアをしている齊藤です。Railsで外部キーのカラムを追加する際に、reference型を使うことがあると思います。reference型の使い方…

validation

モデルの作成後はvalidationを追加する。

class Group < ApplicationRecord
  has_many :members
  validates :name, presence: true
end

HAML

-と=
基本的にerbの<% %>と<%= %>に相当。

ruby

array.pop

配列の最後の要素を削除。
slice, delete_at, shift等

コメント