DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

Ash - Create with relationship

Ok been stuck on this thing :D I have this resource:

defmodule NoSpark.Builder.Din do
  use Ash.Resource,
    data_layer: AshSqlite.DataLayer

  sqlite do
    table "dins"
    repo NoSpark.Repo
  end

  attributes do
    uuid_primary_key :id

    attribute :label, :string
    attribute :description, :string

    attribute :slots, :integer do
      allow_nil? false
      constraints min: 0
    end
  end

  relationships do
    belongs_to :schema, NoSpark.Builder.Schema
  end

  code_interface do
    define_for(NoSpark.Builder)

    define(:create)
    define(:read)
    define(:update)
  end

  actions do
    defaults [:create, :read, :update, :destroy]
  end
end
Enter fullscreen mode Exit fullscreen mode

And i want to create the din with a schema already attached.

All you really need to do is update the relationship belongs_to to make it writable:

    belongs_to :schema, NoSpark.Builder.Schema do
      attribute_writable? true
    end
Enter fullscreen mode Exit fullscreen mode

And now you can create your resource with the schema relationship attached like so:

Din.create!(%{label: "Din X", slots: schema.slots, schema_id: schema.id})
Enter fullscreen mode Exit fullscreen mode

Where schema is just some schema which is already created.

This took me a while to figure out :D Hope this helps you!

Top comments (0)