LoginSignup
11
13

More than 5 years have passed since last update.

Railsで同一モデルに一対多/多対多の関連付けをしたときに躓いたところ

Last updated at Posted at 2017-05-07

ユーザー(user)は複数の記事(article)を保持する
ユーザー(user)は中間テーブル(favorite_relation)を通じて、複数の記事(article)をお気に入りとして所持する。

上記のような関連付けを実装しようとした際、教科書通りの記載を行うと下記のようになります。

class User < ApplicationRecord
...
  has_many :articles,dependent: :destroy

  has_many :articles,through: :favorite_relation
  has_many :favorite_relation, dependent: :destroy
...
end

が、当然このような記載を行うと、articlesで呼び出したときの対象の名称が重複してしまう度、エラー及び予期せぬ動作を引き起こしました。

# ユーザーの記事?ユーザーがお気に入り登録している記事?
@user.articles

そのようなときはエイリアスを付与して、中間テーブルを介して取得するモデルをsourceで指定します。

class User < ApplicationRecord
...
  has_many :articles,dependent: :destroy

  has_many :favorite_articles,through: :favorite_relation,source: :article
  has_many :favorite_relation, dependent: :destroy
...
end

これで想定通りの実装を行うことができました。

# ユーザーの記事
@user.articles
# ユーザーがお気に入り登録している記事
@user.favorite_articles

まとめ

説明の不備・不足等ございましたら、ご指摘いただけますと助かります。

11
13
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
11
13