LoginSignup
4
5

More than 5 years have passed since last update.

【Rails】レビュー前 確認チェックシート

Posted at

レビューの際によく指摘される点をまとめてみました。

リンク先はPrefixで書く

リンク先を URI Patternで書いていませんか? Prefixで書きましょう。Prefixは(bundle exec) rake routesで確認できます。

例:
× redirect_to "/groups/#{@group.id}/messages"
redirect_to group_messages_path(@group)

renderを使う

レコード保存失敗時など、同じページに戻したい時はredirect_toではなくrenderを使うことで処理を早めることができます。ただし、renderはviewを呼び出すだけでコントローラーは経由しないので、renderを使う際は呼び出すviewで使われる変数を定義する必要があります。

例:indexアクションのビューに戻る場合
@messages = @group.messagesなどindexにある変数の定義
render :index

部分テンプレートを使う

「ページの左側には常にグループのリストを表示する」など、viewの一部分に同じものを表示する場合は、部分テンプレートを設定し、renderで呼び出すようにすると便利です。また、配列に同じ形式の複数のオブジェクトが入っている場合、collectionを使うと、eachメソッドと同じことができます。

例:

view/groups/content-left
= render partial: 'groups/group-list', collection: @groups, as: :group`
view/groups/_group-list
= link_to group_messages_path(group) do
  .groups
    %p.groups__name
      = group.name
    %p.groups__message
      - if group.messages.present?
        = group.messages.last.body

同じ変数はbefore_actionにまとめる

controllerで同じ変数を複数のアクションで使う場合、アクションごとに変数を定義すると変更があった場合にそれぞれ修正するのが面倒ですよね。同じ変数はbefore_actionにまとめましょう。

例:

messages_controller.rb
 before_action :index_variables, only: [:index, :create]

 def index_variables
    @groups = current_user.groups.order(created_at: :DESC)
    @group = Group.find(params[:group_id])
    @users = @group.users
    @messages = @group.messages.order(created_at: :DESC).includes(:user)
  end

rollbackしてテーブルの内容を変更する

ターミナルでrails g migration AddImageToMessages image:stringなどと入力すると、テーブルに新しいカラムを追加することだできますが、後からテーブルを確認する時に分かりづらいですね。rake db:rollbackしてから元のファイルを変更し、rake db:migrateするとようにしましょう。

外部キーはreferencesとforeign_keyで設定する

外部キー(他のテーブルのid)のカラムが必要な場合はreferencesで関連づけましょう。また、オプションにforeign_keyを記述することで、クラス名から外部キーの名前を自動的に作成してくれます。

例:group table と user table を外部キーに設定したい場合

class CreateMessages < ActiveRecord::Migration[5.0]
  def change
    create_table :messages do |t|
      t.text :body, null: false
      t.string :image
      t.references :group, foreign_key: true
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end

適切な位置にgemを記述する

gemを導入する場合、どの環境に必要なのかを考えて適切な場所に記述しましょう。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5