LoginSignup
0
1

More than 3 years have passed since last update.

Rails コーティング規約について 1

Posted at

はじめに

Ruby、Railsの基礎を学習中の方に向けて記載致します。
Rubyのコーティング規約はコチラをクリック願います。
私自身これからチーム開発を行う上で大事にしたい。知っておきたいことをOutputします。

Routing

ActiveRecordのモデル間の関連を表現するには、入れ子型でルートを定義する。

qiita.rb
class Post < ActiveRecord::Base
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :post
end

# routes.rb
resources :posts do
  resources :comments
end

ActiveRecord

なるべくhas_and_belongs_to_manyよりhas_many :throughを利用する。

qiita.rb
# あまり良くない例
class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
end

# 良い例
class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, through: :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships
end

さいごに

コーティング規約については毎日更新します。
皆様の復習等にご活用頂けますと幸いです。

0
1
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
0
1