1
votes
defmodule ParrotApi.Meetup do

    schema "meetups" do
      field :timestamp, :integer
      belongs_to :topic, ParrotApi.Topic

      timestamps()
    end


    @required_fields ~w(timestamp)

    def changeset(struct, params \\ %{}) do
      struct
      |> cast(params, @required_fields)
      |> cast_assoc(:topic, required: true)
      |> validate_required(@required_fields)
    end

end

But when I do this in my tests:

%Meetup{timestamp: future_time, topic_id: topic.id} |> Repo.insert

it doesn't through an error:

iex(10)> %Meetup{timestamp: 123123} |> Repo.insert
[debug] QUERY OK db=0.3ms
begin []
[debug] QUERY OK db=1.3ms
INSERT INTO "meetups" ("timestamp","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" [123123, {{2017, 4, 13}, {12, 3, 24, 644065}}, {{2017, 4, 13}, {12, 3, 24, 644074}}]
[debug] QUERY OK db=1.6ms
commit []
{:ok,
 %ParrotApi.Meetup{__meta__: #Ecto.Schema.Metadata<:loaded, "meetups">, id: 6,
  inserted_at: ~N[2017-04-13 12:03:24.644065], timestamp: 123123,
  topic: #Ecto.Association.NotLoaded<association :topic is not loaded>,
  topic_id: nil, updated_at: ~N[2017-04-13 12:03:24.644074]}}
iex(11)>

How do I ensure that Meetups are only made with a topic_id present??

1
Ecto validations won't be run if you create a Struct directly and send it to the database. You need to add this constraint to the database field for that. - Dogbert
Sorry I'm new to Ecto. Is there another way of creating a Meetup? I thought that was the syntax for it - bigpotato
Yes, Meetup.changeset(%Meetup{}, %{timestamp: 123123}) |> Repo.insert. - Dogbert
Hm it is telling me ** (ArgumentError) could not convert the parameter 'timestamp,' into an atom, 'timestamp,' is not a schema field - bigpotato
nvm fixed it! it didn't like @required_fields in my model. Thanks!!! - bigpotato

1 Answers

1
votes

Try using atoms for your fields instead of strings. I think required_fields wants atoms. Also, if you want the topic_id to be added, you need to list that field also. Just change to @required_fields ~w(timestamp topic_id)a. Also try calling required_fields right after your cast call.