0

I'm having trouble with Elixir/Phoenix documentation, so I thought I'd ask here.

I created a table called boards with some text fields (:title, :owner, etc). I now want to create a migration that will add a new field to it, that will contain multiple records of a new members table.

What is the correct syntax for the migration file? How do I edit the boards.ex? Is there a particular location new files need to be, i.e. does the members definition need to be in boards.ex?

  • 2
    Don't. Storing multiple values in a single column is recipe for disaster. Create a properly normalized model with a one-to-many relationship. –  Feb 05 '21 at 08:18
  • @a_horse_with_no_name Oh, that is so cool. Thanks and +1. Somewhat related, when I try to show the list of members in an html, I get the `` error. What function do I use to preload it? And where do I put it? `board.ex`? – Stevo Ilišković Feb 05 '21 at 13:48
  • @StevoIlišković you need to `|> preload(:members)` in your query, to see the association. – copser Feb 10 '21 at 07:19

1 Answers1

0

Here is the code that got it working:

# \lib\vision\boards\board.ex
defmodule Vision.Boards.Board do
  use Ecto.Schema
  import Ecto.Changeset

  schema "boards" do
    field :owner, :string
    field :team_name, :string
    field :title, :string
    has_many :members, Vision.Members.Member

    timestamps()
  end

  @doc false
  def changeset(board, attrs) do
    board
    |> cast(attrs, [:title, :owner, :team_name])
    |> validate_required([:title, :owner, :team_name])
  end
end

# \lib\vision\members\member.ex
defmodule Vision.Members.Member do
  use Ecto.Schema
  import Ecto.Changeset

  schema "members" do
    field :role, :string
    field :username, :string
    belongs_to :board, Vision.Boards.Board    

    timestamps()
  end

  @doc false
  def changeset(member, attrs) do
    member
    |> cast(attrs, [:username, :role])
    |> validate_required([:username, :role])
  end
end

And then in a migration:

# \priv\repo\migrations\*_member_belongs_to_board.exs
defmodule Vision.Repo.Migrations.MemberBelongsToBoard do
  use Ecto.Migration

  def change do
    alter table(:members) do
        add :board_id, references (:boards)
    end
  end
end