Limiting how many has_many associations

Hi! i have a has_many association, but i want to know how many associations i have and limit how many of these are allowed, is there a way to do this? thanks!

Take a look at Ecto.Changeset.validate_length for validating length of lists in general, including associations.

2 Likes

i have a class that can have many students, something like this ->

schema "classes" do
  field :class, :string
  field :period, :string
  has_many :students, School.Student

  timestamps()
end

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, [:class, :period])
  |> validate_required([:class, :period])
  |> validate_length(:students, max: 5)
end

i tried validate_length(:students, max: 5) like you said to limit the number of students but it doesn’t seem to work, am i forgetting something?

Can you please detail what you mean by “it doesn’t seem to work”? Also, can you make sure you are preloading the students before running the changeset?

1 Like

i mean that i can still associate unlimited students to the class, even with |> validate_length(:students, max: 5), im using Repo.get!(Class, id) |> Repo.preload([:students]) to preload the students

How are you associating students to classes? I didn’t see cast_assoc or similar functions in the changeset implementation you posted above.