Search code examples
elixirphoenix-frameworkecto

Can two models have two types of relationships through two fields?


I'm building a chat room application where the two primary models are User and Room. Now, a user can create new rooms, as well as belong to existing rooms. So I ended up with the following model for rooms:

defmodule Elemental.TxChat.Room do
  use Elemental.TxChat.Web, :model

  schema "rooms" do
    field :name, :string
    field :created_at, Ecto.DateTime

    # Foreign key indicating which user created this room
    # One user can create any number of rooms 
    belongs_to :created_by, Elemental.TxChat.User
    field :created_from_app, :integer

    many_to_many :members, Elemental.TxChat.User, join_through: "rooms_users"

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:name, :created_at, :created_by, :created_from_app])
    |> validate_required([:name, :created_at, :created_by, :created_from_app])
  end
end

My confusion is, it now looks like there are two kinds of relationships between User and Room: Many to one, and many to many. A colleague suggested that I remove the belongs_to field and replace it with a simple integer field, but then I don't want to lose the benefits of foreign key check at DB level.

How can this situation be resolved?


Solution

  • As pointed by @Dogbert in the comments, it is perfectly fine to have multiple relationships between two schemas.