خرید بک لینک

Vote count: 0

I have a User and a Group model (user has_many groups). When a new User is created I want to build three default groups for that user. Lets call them x, y and z (which would be the name).

I guess Ecto.Changeset.put_assoc is the right tool for this job. Correct? How can I use it to create the groups in the create function?

web/controllers/user_controller.ex

[...]
def create(co, %{"user" => user_params}) do
  changeset = User.changeset(%User{}, user_params)

  case Repo.insert(changeset) do
    {:ok, user} ->
      co
      |> MyApp.Auth.login(user)
      |> put_flash(:info, "User created successfully.")
      |> redirect(to: user_path(co, :show, user))
    {:error, changeset} ->
      render(co, "new.html", changeset: changeset)
  end
end
[...]

web/models/user.ex

defmodule MyApp.User do
  use MyApp.Web, :model
  use Arc.Ecto.Model

  schema "users" do
    field :first_name, :string
    field :last_name, :string

    has_many :groups, MyApp.Group
[...]

web/models/group.ex

defmodule MyApp.Group do
  use MyApp.Web, :model

  schema "groups" do
    field :name, :string

    belongs_to :user, MyApp.User
[...]

asked 2 mins ago

برچسب: نویسنده: استخدام کار تاريخ: دوشنبه 20 ارديبهشت 1395 ساعت: 0:14

صفحه بندی