code-corps / code-corps-api

Elixir/Phoenix API for Code Corps.
https://www.codecorps.org
MIT License
234 stars 86 forks source link

Fix long description validation #1263

Open joshsmith opened 6 years ago

joshsmith commented 6 years ago

Problem

EDIT: See the comment below.

We want to have a place for a Project to be explicitly approved by an admin.

begedin commented 6 years ago

This is pretty much done, in that the update action now supports setting approved: true on projects, and this change is only allowed by the policy if the user performing it is an admin.

The one thing we need to deal with, and this is a difficulty I've encountered while working on https://github.com/code-corps/code-corps-ember/pull/1576

def changeset(struct, params) do
  struct
  |> cast(params, [:approval_requested, :cloudinary_public_id, :default_color, :description, :long_description_markdown, :title, :website])
  |> prefix_url(:website)
  |> validate_format(:website, CodeCorps.Helpers.URL.valid_format())
  |> validate_required([:title])
  |> generate_slug(:title, :slug)
  |> validate_slug(:slug)
  |> unique_constraint(:slug, name: :index_projects_on_slug)
  # this throws a validation error on update
  |> check_constraint(:long_description_markdown,
                      message: "cannot be deleted once your project is approved",
                      name: "set_long_description_markdown_if_approved")
  |> MarkdownRendererService.render_markdown_to_html(:long_description_markdown, :long_description_body)
end

The constraint is defined as

create constraint(
  :projects, 
  "set_long_description_markdown_if_approved", 
  check: "long_description_markdown IS NOT NULL OR approved = false")

What happens is

We need to either

Adding a custom clause or subclause to Projects.update won't work, because the constraint is at db level, so will trigger in all cases.