My models have a lot of associations and I’m trying to build search forms with filters to filter by not only fields of the entity’s schema but also by fields of it’s associations.
If I understood correctly, I can’t interpolate the association name into the :as key of the join and into the bindings of the where functions, I mean I can’t do something like that (correct me if I’m wrong!!):
def ensure_association(query, assoc) do if has_named_binding?(query, assoc) do query else join(query, [p], c in assoc(p, ^assoc), as: ^assoc) end end
Nor I can do this:
def add_where(query, association, field_name, value) do where(query, [^association: q], field(q, ^field_name) == ^value) end
So I tried to overcome this like this:
defmodule Jp.Search do import Ecto.query for association <- ~w(address skype phones events subscriptions notifications actions assignments notes company specialist agent vacancies offers contract contracts driving_licence general_skills materials work_experiences professional_schools professional_courses professional_certificates welder concreter machine_operator cnc_experiences turner_cutter)a do def add_where(query, unquote(association), field_name, value) do where(query, [unquote(association): q], field(q, ^field_name) == ^value) end def ensure_association(query, unquote(association)) do has_named_binding?(query, unquote(association)) && query || join(query, :inner, [q], a in assoc(p, unquote(association)), as: unquote(association)) end end end
But it doesn’t compile, giving me error:
unexpected token: ":"
on the line where I try to put association name into binding like [unquote(association): q]
I also tried to put it like [unquote(to_string(association)):q]
but the error persists.
So how to do it properly and what do I do wrong?