Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

postgresql - What is the correct syntax when creating new column containing multiple records

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?

question from:https://stackoverflow.com/questions/66059580/what-is-the-correct-syntax-when-creating-new-column-containing-multiple-records

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the code that got it working:

# libvisionoardsoard.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

# libvisionmembersmember.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
epomigrations*_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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...