Bitwise
Bitwise

Reputation: 8461

Create two models with one create

While creating a League I'm trying to also create a join association called UsersLeagues. Here is my current attempt:

def changeset(struct, params \\ %{}) do
    struct
      |> cast(params, [:name])
      |> validate_required([:name])
      |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{}, user_id: 1, league_id: 1, commissioner: true))
end

When I try to create with that changeset I get this error. expected params to be a :map, got: [user_id: 1, league_id: 1, commissioner: true]

I'm not sure what it's trying to tell me?

Again, I'm trying to create one model and in that process create a join table.

Upvotes: 0

Views: 130

Answers (2)

notriddle
notriddle

Reputation: 668

The second argument to UserLeagues is supposed to be a map, but it's a keyword list. Change the second-to-last line to this:

  |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{}, %{user_id: 1, league_id: 1, commissioner: true}))

Upvotes: 0

script
script

Reputation: 2167

def changeset(struct, params \\ %{}) do
struct
  |> cast(params, [:name])
  |> validate_required([:name])
  |> put_assoc(:users_leagues,UsersLeagues.changeset(%UsersLeagues{user_id: 1, league_id: 1, commissioner: true}))
end

try this

Changeset is used to validate data before insert it into the data base.

Upvotes: 1

Related Questions