Copy & Paste Engineer

【Elixir】Ecto で色々な関係の設定

【Elixir】Ecto で色々な関係の設定

Elixir の Ecto で色々な関連設定について詳しく解説します。 has_one, has_many, belongs_to, throughオプションに焦点を当てます。

その他のオプションについても以下のページで確認できますのでご参考にどうぞ Ecto.Schema

基本的な has_oneの使い方

has_one/3

defmodule Post do
  use Ecto.Schema

  schema "posts" do
    has_one :permalink, Permalink
  end
end

カラム名

カラム名のカスタマイズ

foreign_key を指定することで自分のテーブルのカラム名を指定できます。

has_one :permalink, Permalink, foreign_key: :custom_post_id

相手先のIDの指定

references を指定することで自分のテーブルのカラム名を指定できます。

has_one :permalink, Permalink, references: :custom_id, foreign_key: :post_id

where オプションの使用

wherehas_one する際に条件が付与されます。

has_one :active_permalink, Permalink, where: [deleted_at: nil]

where は他の関連でも使用可能

このwhereオプションはhas_oneだけでなく、has_manybelongs_toなど、他の関連でも使用できます。

through オプションの使用

has_many/has_one :through

has_many :comments_authors, through: [:comments, :author]

この設定では、PostCommentを経由してAuthorに関連していると定義されます。

has_many と belongs_to の違い

has_many

has_many/3

# Postモデル
schema "posts" do
  has_many :comments, Comment
end

belongs_to

belongs_to/3

# Commentモデル
schema "comments" do
  belongs_to :post, Post
end

共通点と相違点

まとめ

Ectoは非常に柔軟な設定が可能で、これらのオプションを駆使することで、さまざまな要件に対応できます。