vt-elixir / ja_resource

A behaviour to reduce boilerplate code in your JSON-API compliant Phoenix controllers without sacrificing flexibility.
Other
113 stars 33 forks source link

Using ja_resource with has_many #45

Closed joshuataylor closed 7 years ago

joshuataylor commented 7 years ago

So I have a schema with a has_many, and passing that information through with relationships in a JSON API Resource produces the following with ja_resource:

%{"foo_ids" => [1,2,3,4]}

Now this is fine, but is there a "standard" way to process this in a changeset, or do I have to write this myself in each schemas changeset?

We should also add this to the docs.

joshuataylor commented 7 years ago

Here's the workaround I ended up doing:

      def process_has_many(struct, params, schema, field, key) do
        case Map.has_key?(params, key) do
          true ->
            results = schema |> where([p], p.id in ^params[key]) |> Repo.all
            struct |> Ecto.Changeset.put_assoc(field, results)
          false ->
            struct
        end
      end

And then in my changeset:

|> process_has_many(params, Post, :posts, "post_ids")
alanpeabody commented 7 years ago

You will have to handle this yourself as you did above or some other way. ✔️

emwalker commented 7 years ago

@alanpeabody is there any plan to support the JSON API spec for modifying relationships?

http://jsonapi.org/format/#crud-updating-relationships

alanpeabody commented 7 years ago

Not currently... It actually isn't a feature I have ever used.