View Source DSL: Ash.Resource.Dsl

attributes

A section for declaring attributes on the resource.

Nested DSLs

Examples

attributes do
  uuid_primary_key :id

  attribute :first_name, :string do
    allow_nil? false
  end

  attribute :last_name, :string do
    allow_nil? false
  end

  attribute :email, :string do
    allow_nil? false

    constraints [
      match: ~r/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/
    ]
  end

  attribute :type, :atom do
    constraints [
      one_of: [:admin, :teacher, :student]
    ]
  end

  create_timestamp :inserted_at
  update_timestamp :updated_at
end

attributes.attribute

attribute name, type

Declares an attribute on the resource.

Examples

attribute :name, :string do
  allow_nil? false
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the attribute.
typemoduleThe type of the attribute. See Ash.Type for more.

Options

NameTypeDefaultDocs
constraintsKeyword.tConstraints to provide to the type when casting the value. For more, see the constraints topic.
descriptionString.tAn optional description for the attribute.
sensitive?booleanfalseWhether or not the attribute value contains sensitive information, like PII. See the Security guide for more.
sourceatomIf the field should be mapped to a different name in the data layer. Support varies by data layer.
always_select?booleanfalseWhether or not to ensure this attribute is always selected when reading from the database, regardless of applied select statements.
primary_key?booleanfalseWhether the attribute is the primary key. Composite primary key is also possible by using primary_key? true in more than one attribute. If primary_key? is true, allow_nil? must be false.
allow_nil?booleantrueWhether or not the attribute can be set to nil. If nil value is given error is raised.
generated?booleanfalseWhether or not the value may be generated by the data layer.
writable?booleantrueWhether or not the value can be written to. Non-writable attributes can still be written with Ash.Changeset.force_change_attribute/3.
private?booleanfalseThe attribute is not publically writable, and should not be exposed over any public interfaces. See the security guide for more.
default(-> any) | mfa | any()A value to be set on all creates, unless a value is being provided already.
update_default(-> any) | mfa | any()A value to be set on all updates, unless a value is being provided already.
filterable?boolean | :simple_equalitytrueWhether or not the attribute can be referenced in filters.
match_other_defaults?booleanfalseEnsures that other attributes that use the same "lazy" default (a function or an mfa), use the same default value. Has no effect unless default is a zero argument function.

Introspection

Target: Ash.Resource.Attribute

attributes.create_timestamp

create_timestamp name

Declares a non-writable attribute with a create default of &DateTime.utc_now/0

Accepts all the same options as Ash.Resource.Dsl.attributes.attribute, except it sets the following different defaults:

writable? false private? true default &DateTime.utc_now/0 match_other_defaults? true type Ash.Type.UTCDatetimeUsec allow_nil? false

Examples

create_timestamp :inserted_at

Arguments

NameTypeDefaultDocs
nameatomThe name of the attribute.

Options

NameTypeDefaultDocs
typemoduleAsh.Type.UtcDatetimeUsecThe type of the attribute. See Ash.Type for more.
constraintsKeyword.tConstraints to provide to the type when casting the value. For more, see the constraints topic.
descriptionString.tAn optional description for the attribute.
sensitive?booleanfalseWhether or not the attribute value contains sensitive information, like PII. See the Security guide for more.
sourceatomIf the field should be mapped to a different name in the data layer. Support varies by data layer.
always_select?booleanfalseWhether or not to ensure this attribute is always selected when reading from the database, regardless of applied select statements.
primary_key?booleanfalseWhether the attribute is the primary key. Composite primary key is also possible by using primary_key? true in more than one attribute. If primary_key? is true, allow_nil? must be false.
allow_nil?booleanfalseWhether or not the attribute can be set to nil. If nil value is given error is raised.
generated?booleanfalseWhether or not the value may be generated by the data layer.
writable?booleanfalseWhether or not the value can be written to. Non-writable attributes can still be written with Ash.Changeset.force_change_attribute/3.
private?booleantrueThe attribute is not publically writable, and should not be exposed over any public interfaces. See the security guide for more.
default(-> any) | mfa | any()&DateTime.utc_now/0A value to be set on all creates, unless a value is being provided already.
update_default(-> any) | mfa | any()A value to be set on all updates, unless a value is being provided already.
filterable?boolean | :simple_equalitytrueWhether or not the attribute can be referenced in filters.
match_other_defaults?booleantrueEnsures that other attributes that use the same "lazy" default (a function or an mfa), use the same default value. Has no effect unless default is a zero argument function.

Introspection

Target: Ash.Resource.Attribute

attributes.update_timestamp

update_timestamp name

Declares a non-writable attribute with a create and update default of &DateTime.utc_now/0

Accepts all the same options as Ash.Resource.Dsl.attributes.attribute, except it sets the following different defaults:

writable? false private? true default &DateTime.utc_now/0 match_other_defaults? true update_default &DateTime.utc_now/0 type Ash.Type.UTCDatetimeUsec allow_nil? false

Examples

update_timestamp :updated_at

Arguments

NameTypeDefaultDocs
nameatomThe name of the attribute.

Options

NameTypeDefaultDocs
typemoduleAsh.Type.UtcDatetimeUsecThe type of the attribute. See Ash.Type for more.
constraintsKeyword.tConstraints to provide to the type when casting the value. For more, see the constraints topic.
descriptionString.tAn optional description for the attribute.
sensitive?booleanfalseWhether or not the attribute value contains sensitive information, like PII. See the Security guide for more.
sourceatomIf the field should be mapped to a different name in the data layer. Support varies by data layer.
always_select?booleanfalseWhether or not to ensure this attribute is always selected when reading from the database, regardless of applied select statements.
primary_key?booleanfalseWhether the attribute is the primary key. Composite primary key is also possible by using primary_key? true in more than one attribute. If primary_key? is true, allow_nil? must be false.
allow_nil?booleanfalseWhether or not the attribute can be set to nil. If nil value is given error is raised.
generated?booleanfalseWhether or not the value may be generated by the data layer.
writable?booleanfalseWhether or not the value can be written to. Non-writable attributes can still be written with Ash.Changeset.force_change_attribute/3.
private?booleantrueThe attribute is not publically writable, and should not be exposed over any public interfaces. See the security guide for more.
default(-> any) | mfa | any()&DateTime.utc_now/0A value to be set on all creates, unless a value is being provided already.
update_default(-> any) | mfa | any()&DateTime.utc_now/0A value to be set on all updates, unless a value is being provided already.
filterable?boolean | :simple_equalitytrueWhether or not the attribute can be referenced in filters.
match_other_defaults?booleantrueEnsures that other attributes that use the same "lazy" default (a function or an mfa), use the same default value. Has no effect unless default is a zero argument function.

Introspection

Target: Ash.Resource.Attribute

attributes.integer_primary_key

integer_primary_key name

Declares a generated, non writable, non-nil, primary key column of type integer.

Generated integer primary keys must be supported by the data layer.

Accepts all the same options as Ash.Resource.Dsl.attributes.attribute, except for allow_nil?, but it sets the following different defaults:

writable? false primary_key? true generated? true type :integer

Examples

integer_primary_key :id

Arguments

NameTypeDefaultDocs
nameatomThe name of the attribute.

Options

NameTypeDefaultDocs
typemodule:integerThe type of the attribute. See Ash.Type for more.
constraintsKeyword.tConstraints to provide to the type when casting the value. For more, see the constraints topic.
descriptionString.tAn optional description for the attribute.
sensitive?booleanfalseWhether or not the attribute value contains sensitive information, like PII. See the Security guide for more.
sourceatomIf the field should be mapped to a different name in the data layer. Support varies by data layer.
always_select?booleanfalseWhether or not to ensure this attribute is always selected when reading from the database, regardless of applied select statements.
primary_key?booleantrueWhether the attribute is the primary key. Composite primary key is also possible by using primary_key? true in more than one attribute. If primary_key? is true, allow_nil? must be false.
generated?booleantrueWhether or not the value may be generated by the data layer.
writable?booleanfalseWhether or not the value can be written to. Non-writable attributes can still be written with Ash.Changeset.force_change_attribute/3.
private?booleanfalseThe attribute is not publically writable, and should not be exposed over any public interfaces. See the security guide for more.
default(-> any) | mfa | any()A value to be set on all creates, unless a value is being provided already.
update_default(-> any) | mfa | any()A value to be set on all updates, unless a value is being provided already.
filterable?boolean | :simple_equalitytrueWhether or not the attribute can be referenced in filters.
match_other_defaults?booleanfalseEnsures that other attributes that use the same "lazy" default (a function or an mfa), use the same default value. Has no effect unless default is a zero argument function.

Introspection

Target: Ash.Resource.Attribute

attributes.uuid_primary_key

uuid_primary_key name

Declares a non writable, non-nil, primary key column of type uuid, which defaults to Ash.UUID.generate/0.

Accepts all the same options as Ash.Resource.Dsl.attributes.attribute, except for allow_nil?, but it sets the following different defaults:

writable? false default &Ash.UUID.generate/0 primary_key? true generated? true type :uuid

Examples

uuid_primary_key :id

Arguments

NameTypeDefaultDocs
nameatomThe name of the attribute.

Options

NameTypeDefaultDocs
typemodule:uuidThe type of the attribute. See Ash.Type for more.
constraintsKeyword.tConstraints to provide to the type when casting the value. For more, see the constraints topic.
descriptionString.tAn optional description for the attribute.
sensitive?booleanfalseWhether or not the attribute value contains sensitive information, like PII. See the Security guide for more.
sourceatomIf the field should be mapped to a different name in the data layer. Support varies by data layer.
always_select?booleanfalseWhether or not to ensure this attribute is always selected when reading from the database, regardless of applied select statements.
primary_key?booleantrueWhether the attribute is the primary key. Composite primary key is also possible by using primary_key? true in more than one attribute. If primary_key? is true, allow_nil? must be false.
generated?booleanfalseWhether or not the value may be generated by the data layer.
writable?booleanfalseWhether or not the value can be written to. Non-writable attributes can still be written with Ash.Changeset.force_change_attribute/3.
private?booleanfalseThe attribute is not publically writable, and should not be exposed over any public interfaces. See the security guide for more.
default(-> any) | mfa | any()&Ash.UUID.generate/0A value to be set on all creates, unless a value is being provided already.
update_default(-> any) | mfa | any()A value to be set on all updates, unless a value is being provided already.
filterable?boolean | :simple_equalitytrueWhether or not the attribute can be referenced in filters.
match_other_defaults?booleanfalseEnsures that other attributes that use the same "lazy" default (a function or an mfa), use the same default value. Has no effect unless default is a zero argument function.

Introspection

Target: Ash.Resource.Attribute

relationships

A section for declaring relationships on the resource.

Relationships are a core component of resource oriented design. Many components of Ash will use these relationships. A simple use case is loading relationships (done via the Ash.Query.load/2).

See the relationships guide for more.

Nested DSLs

Examples

relationships do
  belongs_to :post, MyApp.Post do
    primary_key? true
  end

  belongs_to :category, MyApp.Category do
    primary_key? true
  end
end
relationships do
  belongs_to :author, MyApp.Author

  many_to_many :categories, MyApp.Category do
    through MyApp.PostCategory
    destination_attribute_on_join_resource :category_id
    source_attribute_on_join_resource :post_id
  end
end
relationships do
  has_many :posts, MyApp.Post do
    destination_attribute :author_id
  end

  has_many :composite_key_posts, MyApp.CompositeKeyPost do
    destination_attribute :author_id
  end
end

relationships.has_one

has_one name, destination

Declares a has_one relationship. In a relational database, the foreign key would be on the other table.

Generally speaking, a has_one also implies that the destination table is unique on that foreign key.

See the relationships guide for more.

Examples

# In a resource called `Word`
has_one :dictionary_entry, DictionaryEntry do
  source_attribute :text
  destination_attribute :word_text
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the relationship
destinationmoduleThe destination resource

Options

NameTypeDefaultDocs
manual(any, any -> any) | moduleA module that implements Ash.Resource.ManualRelationship. Also accepts a 2 argument function that takes the source records and the context.
no_attributes?booleanAll existing entities are considered related, i.e this relationship is not based on any fields, and source_attribute and destination_attribute are ignored. See the See the relationships guide for more.
allow_nil?booleantrueMarks the relationship as required. Has no effect on validations, but can inform extensions that there will always be a related entity.
from_many?booleanfalseSignal that this relationship is actually a has_many where the first record is given via the sort. This will allow data layers to properly deduplicate when necessary.
descriptionString.tAn optional description for the relationship
destination_attributeatomThe attribute on the related resource that should match the source_attribute configured on this resource.
validate_destination_attribute?booleantrueWhether or not to validate that the destination field exists on the destination resource
source_attributeatom:idThe field on this resource that should match the destination_attribute on the related resource.
relationship_contextanyContext to be set on any queries or changesets generated for managing or querying this relationship.
private?booleanfalseWhether or not the relationship will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql See the security guide for more.
not_found_messageString.tA message to show if there is a conflict with this relationship in the database on update or create, or when managing relationships.
writable?booleantrueWhether or not the relationship may be managed.
read_actionatomThe read action on the destination resource to use when loading data and filtering.
apiatomThe API module to use when working with the related entity.
filteranyA filter to be applied when reading the relationship.
filterable?booleantrueIf set to false, the relationship will not be usable in filters.
sortanyA sort statement to be applied when loading the relationship.
could_be_related_at_creation?booleanfalseWhether or not related values may exist for this relationship at creation.
violation_messageString.tA message to show if there is a conflict with this relationship in the database on destroy.

Introspection

Target: Ash.Resource.Relationships.HasOne

relationships.has_many

has_many name, destination

Declares a has_many relationship. There can be any number of related entities.

See the relationships guide for more.

Examples

# In a resource called `Word`
has_many :definitions, DictionaryDefinition do
  source_attribute :text
  destination_attribute :word_text
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the relationship
destinationmoduleThe destination resource

Options

NameTypeDefaultDocs
manual(any, any -> any) | moduleA module that implements Ash.Resource.ManualRelationship. Also accepts a 2 argument function that takes the source records and the context.
no_attributes?booleanAll existing entities are considered related, i.e this relationship is not based on any fields, and source_attribute and destination_attribute are ignored. See the See the relationships guide for more.
descriptionString.tAn optional description for the relationship
destination_attributeatomThe attribute on the related resource that should match the source_attribute configured on this resource.
validate_destination_attribute?booleantrueWhether or not to validate that the destination field exists on the destination resource
source_attributeatom:idThe field on this resource that should match the destination_attribute on the related resource.
relationship_contextanyContext to be set on any queries or changesets generated for managing or querying this relationship.
private?booleanfalseWhether or not the relationship will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql See the security guide for more.
not_found_messageString.tA message to show if there is a conflict with this relationship in the database on update or create, or when managing relationships.
writable?booleantrueWhether or not the relationship may be managed.
read_actionatomThe read action on the destination resource to use when loading data and filtering.
apiatomThe API module to use when working with the related entity.
filteranyA filter to be applied when reading the relationship.
filterable?booleantrueIf set to false, the relationship will not be usable in filters.
sortanyA sort statement to be applied when loading the relationship.
could_be_related_at_creation?booleanfalseWhether or not related values may exist for this relationship at creation.
violation_messageString.tA message to show if there is a conflict with this relationship in the database on destroy.

Introspection

Target: Ash.Resource.Relationships.HasMany

relationships.many_to_many

many_to_many name, destination

Declares a many_to_many relationship. Many to many relationships require a join resource.

A join resource is a resource that consists of a relationship to the source and destination of the many to many.

See the relationships guide for more.

Examples

# In a resource called `Word`
many_to_many :books, Book do
  through BookWord
  source_attribute :text
  source_attribute_on_join_resource :word_text
  destination_attribute :id
  destination_attribute_on_join_resource :book_id
end

# And in `BookWord` (the join resource)
belongs_to :book, Book, primary_key?: true, allow_nil?: false
belongs_to :word, Word, primary_key?: true, allow_nil?: false

Arguments

NameTypeDefaultDocs
nameatomThe name of the relationship
destinationmoduleThe destination resource

Options

NameTypeDefaultDocs
throughmoduleThe resource to use as the join resource.
source_attribute_on_join_resourceatomThe attribute on the join resource that should line up with source_attribute on this resource. Defaults to <snake_cased_last_part_of_source_module_name>_id.
destination_attribute_on_join_resourceatomThe attribute on the join resource that should line up with destination_attribute on the related resource. Defaults to <snake_cased_last_part_of_destination_module_name>_id.
join_relationshipatomThe has_many relationship to the join resource. Defaults to <relationship_name>_join_assoc.
descriptionString.tAn optional description for the relationship
destination_attributeatom:idThe attribute on the related resource that should match the source_attribute configured on this resource.
validate_destination_attribute?booleantrueWhether or not to validate that the destination field exists on the destination resource
source_attributeatom:idThe field on this resource that should match the destination_attribute on the related resource.
relationship_contextanyContext to be set on any queries or changesets generated for managing or querying this relationship.
private?booleanfalseWhether or not the relationship will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql See the security guide for more.
not_found_messageString.tA message to show if there is a conflict with this relationship in the database on update or create, or when managing relationships.
writable?booleantrueWhether or not the relationship may be managed.
read_actionatomThe read action on the destination resource to use when loading data and filtering.
apiatomThe API module to use when working with the related entity.
filteranyA filter to be applied when reading the relationship.
filterable?booleantrueIf set to false, the relationship will not be usable in filters.
sortanyA sort statement to be applied when loading the relationship.
could_be_related_at_creation?booleanfalseWhether or not related values may exist for this relationship at creation.
violation_messageString.tA message to show if there is a conflict with this relationship in the database on destroy.

Introspection

Target: Ash.Resource.Relationships.ManyToMany

relationships.belongs_to

belongs_to name, destination

Declares a belongs_to relationship. In a relational database, the foreign key would be on the source table.

This creates a field on the resource with the corresponding name and type, unless define_attribute?: false is provided.

See the relationships guide for more.

Examples

# In a resource called `Word`
belongs_to :dictionary_entry, DictionaryEntry do
  source_attribute :text,
  destination_attribute :word_text
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the relationship
destinationmoduleThe destination resource

Options

NameTypeDefaultDocs
primary_key?booleanfalseWhether the generated attribute is, or is part of, the primary key of a resource.
allow_nil?booleantrueWhether this relationship must always be present, e.g: must be included on creation, and never removed (it may be modified). The generated attribute will not allow nil values.
attribute_writable?booleanfalseWhether the generated attribute will be marked as public & writable.
define_attribute?booleantrueIf set to false an attribute is not created on the resource for this relationship, and one must be manually added in attributes, invalidating many other options.
attribute_typeany:uuidThe type of the generated created attribute. See Ash.Type for more.
descriptionString.tAn optional description for the relationship
destination_attributeatom:idThe attribute on the related resource that should match the source_attribute configured on this resource.
validate_destination_attribute?booleantrueWhether or not to validate that the destination field exists on the destination resource
source_attributeatomThe field on this resource that should match the destination_attribute on the related resource. - Defaults to <name>_id
relationship_contextanyContext to be set on any queries or changesets generated for managing or querying this relationship.
private?booleanfalseWhether or not the relationship will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql See the security guide for more.
not_found_messageString.tA message to show if there is a conflict with this relationship in the database on update or create, or when managing relationships.
writable?booleantrueWhether or not the relationship may be managed.
read_actionatomThe read action on the destination resource to use when loading data and filtering.
apiatomThe API module to use when working with the related entity.
filteranyA filter to be applied when reading the relationship.
filterable?booleantrueIf set to false, the relationship will not be usable in filters.
sortanyA sort statement to be applied when loading the relationship.
violation_messageString.tA message to show if there is a conflict with this relationship in the database on destroy.

Introspection

Target: Ash.Resource.Relationships.BelongsTo

actions

A section for declaring resource actions.

All manipulation of data through the underlying data layer happens through actions. There are four types of action: create, read, update, and destroy. You may recognize these from the acronym CRUD. You can have multiple actions of the same type, as long as they have different names. This is the primary mechanism for customizing your resources to conform to your business logic. It is normal and expected to have multiple actions of each type in a large application.

Nested DSLs

  • action
    • argument
  • create
    • change
    • validate
    • argument
    • metadata
  • read
    • argument
    • prepare
    • pagination
    • metadata
  • update
    • change
    • validate
    • metadata
    • argument
  • destroy
    • change
    • validate
    • metadata
    • argument

Examples

actions do
  create :signup do
    argument :password, :string
    argument :password_confirmation, :string
    validate confirm(:password, :password_confirmation)
    change {MyApp.HashPassword, []} # A custom implemented Change
  end

  read :me do
    # An action that auto filters to only return the user for the current user
    filter [id: actor(:id)]
  end

  update :update do
    accept [:first_name, :last_name]
  end

  destroy do
    change set_attribute(:deleted_at, &DateTime.utc_now/0)
    # This tells it that even though this is a delete action, it
    # should be treated like an update because `deleted_at` is set.
    # This should be coupled with a `base_filter` on the resource
    # or with the read actions having a `filter` for `is_nil: :deleted_at`
    soft? true
  end
end

Options

NameTypeDefaultDocs
defaultslist(:create | :read | :update | :destroy)Creates a simple action of each specified type, with the same name as the type. These will be primary? unless one already exists for that type. Embedded resources, however, have a default of all resource types.
default_acceptlist(atom)A default value for the accept option for each action. Defaults to all public attributes.

actions.action

action name, returns

Declares a generic action. A combination of arguments, a return type and a run function.

For calling this action, see the Ash.Api documentation.

Nested DSLs

Examples

action :top_user_emails, {:array, :string} do
  argument :limit, :integer, default: 10, allow_nil?: false
  run fn input, context ->
    with {:ok, top_users} <- top_users(input.limit) do
      {:ok, Enum.map(top_users, &(&1.email))}
    end
  end
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the action
returnsmoduleThe return type of the action. See Ash.Type for more.

Options

NameTypeDefaultDocs
constraintsKeyword.tConstraints for the return type. See the constriants topic for more.
allow_nil?booleanfalseWhether or not the action can return nil. Unlike attributes & arguments, this defaults to false.
run(any, any -> any) | module
primary?booleanfalseWhether or not this action should be used when no action is specified by the caller.
descriptionString.tAn optional description for the action
transaction?booleanWhether or not the action should be run in transactions. Reads default to false, while create/update/destroy actions default to true.
touches_resourceslist(atom)A list of resources that the action may touch, used when building transactions.

actions.action.argument

argument name, type

Declares an argument on the action

Examples

argument :password_confirmation, :string

Arguments

NameTypeDefaultDocs
nameatomThe name of the argument
typemoduleThe type of the argument. See Ash.Type for more.

Options

NameTypeDefaultDocs
descriptionString.tAn optional description for the argument.
constraintsKeyword.t[]Constraints to provide to the type when casting the value. For more information, see the constraints topic.
allow_nil?booleantrueWhether or not the argument value may be nil (or may be not provided). If nil value is given error is raised.
private?booleanfalseWhether or not the argument should be suppliable by the client.
sensitive?booleanfalseWhether or not the argument value contains sensitive information, like PII. See the security guide for more.
defaultanyThe default value for the argument to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Argument

Introspection

Target: Ash.Resource.Actions.Action

actions.create

create name

Declares a create action. For calling this action, see the Ash.Api documentation.

Nested DSLs

Examples

create :register do
  primary? true
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the action

Options

NameTypeDefaultDocs
allow_nil_inputlist(atom)A list of attributes that would normally be required, but should not be for this action. They will still be validated just before the record is created.
manual(any, any -> any) | moduleOverride the creation behavior. Accepts a module or module and opts, or a function that takes the changeset and context. See the manual actions guide for more.
upsert?booleanfalseForces all uses of this action to be treated as an upsert.
upsert_identityatomThe identity to use for the upsert. Cannot be overriden by the caller. Ignored if upsert? is not set to true.
upsert_fields:replace_all | {:replace, atom | list(atom)} | {:replace_all_except, atom | list(atom)} | atom | list(atom)The fields to overwrite in the case of an upsert. If not provided, all fields except for fields set by defaults will be overwritten.
primary?booleanfalseWhether or not this action should be used when no action is specified by the caller.
descriptionString.tAn optional description for the action
transaction?booleanWhether or not the action should be run in transactions. Reads default to false, while create/update/destroy actions default to true.
touches_resourceslist(atom)A list of resources that the action may touch, used when building transactions.
accept:all | list(atom)The list of attributes to accept. Defaults to all attributes on the resource
delay_global_validations?booleanfalseIf true, global validations will be done in a before_action hook, regardless of their configuration on the resource.
skip_global_validations?booleanfalseIf true, global validations will be skipped. Useful for manual actions.
reject:all | list(atom)A list of attributes not to accept. If this is specified along with accept, these are removed from the accept list.
require_attributeslist(atom)A list of attributes that would normally allow_nil?, to require for this action. No need to include attributes that already do not allow nil?
error_handlermfaSets the error handler on the changeset. See Ash.Changeset.handle_errors/2 for more
manual?booleanInstructs Ash to skip the actual update/create/destroy step at the data layer. See the manual actions guide for more.

actions.create.change

change change

A change to be applied to the changeset.

See Ash.Resource.Change for more.

Examples

change relate_actor(:reporter)
change {MyCustomChange, :foo}

Arguments

NameTypeDefaultDocs
change(any, any -> any) | moduleThe module and options for a change. Also accepts a function that takes the changeset and the context. See Ash.Resource.Change.Builtins for builtin changes.

Options

NameTypeDefaultDocs
only_when_valid?booleanfalseIf the change should only be run on valid changes. By default, all changes are run unless stated otherwise here.
descriptionString.tAn optional description for the change
wherelist((any -> any) | module)[]Validations that should pass in order for this validation to apply. These validations failing will result in this validation being ignored.
always_atomic?booleanfalseBy default, changes are only run atomically if all changes will be run atomically or if there is no change/3 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Change

actions.create.validate

validate validation

Declares a validation to be applied to the changeset.

See Ash.Resource.Validation for more.

Examples

validate changing(:email)

Arguments

NameTypeDefaultDocs
validation(any -> any) | moduleThe module (or module and opts) that implements the Ash.Resource.Validation behaviour. Also accepts a one argument function that takes the changeset.

Options

NameTypeDefaultDocs
where(any -> any) | module | list((any -> any) | module)[]Validations that should pass in order for this validation to apply. Any of these validations failing will result in this validation being ignored.
only_when_valid?booleanfalseIf the validation should only run on valid changes. Useful for expensive validations or validations that depend on valid data.
messageString.tIf provided, overrides any message set by the validation error
descriptionString.tAn optional description for the validation
before_action?booleanfalseIf set to true, the validation will be run in a before_action hook
always_atomic?booleanfalseBy default, validations are only run atomically if all changes will be run atomically or if there is no validate/2 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Validation

actions.create.argument

argument name, type

Declares an argument on the action

Examples

argument :password_confirmation, :string

Arguments

NameTypeDefaultDocs
nameatomThe name of the argument
typemoduleThe type of the argument. See Ash.Type for more.

Options

NameTypeDefaultDocs
descriptionString.tAn optional description for the argument.
constraintsKeyword.t[]Constraints to provide to the type when casting the value. For more information, see the constraints topic.
allow_nil?booleantrueWhether or not the argument value may be nil (or may be not provided). If nil value is given error is raised.
private?booleanfalseWhether or not the argument should be suppliable by the client.
sensitive?booleanfalseWhether or not the argument value contains sensitive information, like PII. See the security guide for more.
defaultanyThe default value for the argument to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Argument

actions.create.metadata

metadata name, type

A special kind of attribute that is only added to specific actions. Nothing sets this value, it must be set in a custom change after_action hook via Ash.Resource.put_metadata/3.

Examples

metadata :api_token, :string, allow_nil?: false
metadata :operation_id, :string, allow_nil?: false

Arguments

NameTypeDefaultDocs
nameatomThe name of the metadata
typeanyThe type of the metadata. See Ash.Type for more.

Options

NameTypeDefaultDocs
constraintsKeyword.t[]Type constraints on the metadata
descriptionString.tAn optional description for the metadata.
allow_nil?booleantrueWhether or not the metadata may return nil
defaultanyThe default value for the metadata to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Metadata

Introspection

Target: Ash.Resource.Actions.Create

actions.read

read name

Declares a read action. For calling this action, see the Ash.Api documentation.

Nested DSLs

Examples

read :read_all do
  primary? true
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the action

Options

NameTypeDefaultDocs
filteranyA filter template that will be applied whenever the action is used. See Ash.Filter for more on templates
manual(any, any, any -> any) | moduleDelegates running of the query to the provided module. Accepts a module or module and opts, or a function that takes the changeset and context. See the manual actions guide for more.
get?booleanfalseExpresses that this action innately only returns a single result. Used by extensions to validate and/or modify behavior. Causes code interfaces to return a single value instead of a list. See the code interface guide for more.
modify_querymfa | (any, any -> any)Allows direct manipulation of the data layer query via an MFA. The ash query and the data layer query will be provided as additional arguments. The result must be {:ok, new_data_layer_query} | {:error, error}.
get_byatom | list(atom)A helper to automatically generate a "get by X" action. Sets get? to true, add args for each of the specified fields, and adds a filter for each of the arguments.
primary?booleanfalseWhether or not this action should be used when no action is specified by the caller.
descriptionString.tAn optional description for the action
transaction?booleanWhether or not the action should be run in transactions. Reads default to false, while create/update/destroy actions default to true.
touches_resourceslist(atom)A list of resources that the action may touch, used when building transactions.

actions.read.argument

argument name, type

Declares an argument on the action

Examples

argument :password_confirmation, :string

Arguments

NameTypeDefaultDocs
nameatomThe name of the argument
typemoduleThe type of the argument. See Ash.Type for more.

Options

NameTypeDefaultDocs
descriptionString.tAn optional description for the argument.
constraintsKeyword.t[]Constraints to provide to the type when casting the value. For more information, see the constraints topic.
allow_nil?booleantrueWhether or not the argument value may be nil (or may be not provided). If nil value is given error is raised.
private?booleanfalseWhether or not the argument should be suppliable by the client.
sensitive?booleanfalseWhether or not the argument value contains sensitive information, like PII. See the security guide for more.
defaultanyThe default value for the argument to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Argument

actions.read.prepare

prepare preparation

Declares a preparation, which can be used to prepare a query for a read action.

Examples

prepare build(sort: [:foo, :bar])

Arguments

NameTypeDefaultDocs
preparation(any, any -> any) | moduleThe module and options for a preparation. Also accepts functions take the query and the context.

Introspection

Target: Ash.Resource.Preparation

actions.read.pagination

Adds pagination options to a resource

Options

NameTypeDefaultDocs
keyset?booleanfalseWhether or not keyset based pagination is supported
offset?booleanfalseWhether or not offset based pagination is supported
default_limitpos_integerThe default page size to apply, if one is not supplied
countabletrue | false | :by_defaultfalseWhether not a returned page will have a full count of all records. Use :by_default to do it automatically.
max_page_sizepos_integer250The maximum amount of records that can be requested in a single page
required?booleantrueWhether or not pagination can be disabled. Only relevant if some pagination configuration is supplied.

Introspection

Target: Ash.Resource.Actions.Read.Pagination

actions.read.metadata

metadata name, type

A special kind of attribute that is only added to specific actions. Nothing sets this value, it must be set in a custom change after_action hook via Ash.Resource.put_metadata/3.

Examples

metadata :api_token, :string, allow_nil?: false
metadata :operation_id, :string, allow_nil?: false

Arguments

NameTypeDefaultDocs
nameatomThe name of the metadata
typeanyThe type of the metadata. See Ash.Type for more.

Options

NameTypeDefaultDocs
constraintsKeyword.t[]Type constraints on the metadata
descriptionString.tAn optional description for the metadata.
allow_nil?booleantrueWhether or not the metadata may return nil
defaultanyThe default value for the metadata to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Metadata

Introspection

Target: Ash.Resource.Actions.Read

actions.update

update name

Declares a update action. For calling this action, see the Ash.Api documentation.

Nested DSLs

Examples

update :flag_for_review, primary?: true

Arguments

NameTypeDefaultDocs
nameatomThe name of the action

Options

NameTypeDefaultDocs
manual(any, any -> any) | moduleOverride the update behavior. Accepts a module or module and opts, or a function that takes the changeset and context. See the manual actions guide for more.
primary?booleanfalseWhether or not this action should be used when no action is specified by the caller.
descriptionString.tAn optional description for the action
transaction?booleanWhether or not the action should be run in transactions. Reads default to false, while create/update/destroy actions default to true.
touches_resourceslist(atom)A list of resources that the action may touch, used when building transactions.
accept:all | list(atom)The list of attributes to accept. Defaults to all attributes on the resource
delay_global_validations?booleanfalseIf true, global validations will be done in a before_action hook, regardless of their configuration on the resource.
skip_global_validations?booleanfalseIf true, global validations will be skipped. Useful for manual actions.
reject:all | list(atom)A list of attributes not to accept. If this is specified along with accept, these are removed from the accept list.
require_attributeslist(atom)A list of attributes that would normally allow_nil?, to require for this action. No need to include attributes that already do not allow nil?
error_handlermfaSets the error handler on the changeset. See Ash.Changeset.handle_errors/2 for more
manual?booleanInstructs Ash to skip the actual update/create/destroy step at the data layer. See the manual actions guide for more.

actions.update.change

change change

A change to be applied to the changeset.

See Ash.Resource.Change for more.

Examples

change relate_actor(:reporter)
change {MyCustomChange, :foo}

Arguments

NameTypeDefaultDocs
change(any, any -> any) | moduleThe module and options for a change. Also accepts a function that takes the changeset and the context. See Ash.Resource.Change.Builtins for builtin changes.

Options

NameTypeDefaultDocs
only_when_valid?booleanfalseIf the change should only be run on valid changes. By default, all changes are run unless stated otherwise here.
descriptionString.tAn optional description for the change
wherelist((any -> any) | module)[]Validations that should pass in order for this validation to apply. These validations failing will result in this validation being ignored.
always_atomic?booleanfalseBy default, changes are only run atomically if all changes will be run atomically or if there is no change/3 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Change

actions.update.validate

validate validation

Declares a validation to be applied to the changeset.

See Ash.Resource.Validation for more.

Examples

validate changing(:email)

Arguments

NameTypeDefaultDocs
validation(any -> any) | moduleThe module (or module and opts) that implements the Ash.Resource.Validation behaviour. Also accepts a one argument function that takes the changeset.

Options

NameTypeDefaultDocs
where(any -> any) | module | list((any -> any) | module)[]Validations that should pass in order for this validation to apply. Any of these validations failing will result in this validation being ignored.
only_when_valid?booleanfalseIf the validation should only run on valid changes. Useful for expensive validations or validations that depend on valid data.
messageString.tIf provided, overrides any message set by the validation error
descriptionString.tAn optional description for the validation
before_action?booleanfalseIf set to true, the validation will be run in a before_action hook
always_atomic?booleanfalseBy default, validations are only run atomically if all changes will be run atomically or if there is no validate/2 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Validation

actions.update.metadata

metadata name, type

A special kind of attribute that is only added to specific actions. Nothing sets this value, it must be set in a custom change after_action hook via Ash.Resource.put_metadata/3.

Examples

metadata :api_token, :string, allow_nil?: false
metadata :operation_id, :string, allow_nil?: false

Arguments

NameTypeDefaultDocs
nameatomThe name of the metadata
typeanyThe type of the metadata. See Ash.Type for more.

Options

NameTypeDefaultDocs
constraintsKeyword.t[]Type constraints on the metadata
descriptionString.tAn optional description for the metadata.
allow_nil?booleantrueWhether or not the metadata may return nil
defaultanyThe default value for the metadata to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Metadata

actions.update.argument

argument name, type

Declares an argument on the action

Examples

argument :password_confirmation, :string

Arguments

NameTypeDefaultDocs
nameatomThe name of the argument
typemoduleThe type of the argument. See Ash.Type for more.

Options

NameTypeDefaultDocs
descriptionString.tAn optional description for the argument.
constraintsKeyword.t[]Constraints to provide to the type when casting the value. For more information, see the constraints topic.
allow_nil?booleantrueWhether or not the argument value may be nil (or may be not provided). If nil value is given error is raised.
private?booleanfalseWhether or not the argument should be suppliable by the client.
sensitive?booleanfalseWhether or not the argument value contains sensitive information, like PII. See the security guide for more.
defaultanyThe default value for the argument to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Argument

Introspection

Target: Ash.Resource.Actions.Update

actions.destroy

destroy name

Declares a destroy action. For calling this action, see the Ash.Api documentation.

Nested DSLs

Examples

destroy :soft_delete do
  primary? true
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the action

Options

NameTypeDefaultDocs
soft?atomfalseIf specified, the destroy action behaves as an update internally
manual(any, any -> any) | moduleOverride the update behavior. Accepts a module or module and opts, or a function that takes the changeset and context. See the manual actions guide for more.
primary?booleanfalseWhether or not this action should be used when no action is specified by the caller.
descriptionString.tAn optional description for the action
transaction?booleanWhether or not the action should be run in transactions. Reads default to false, while create/update/destroy actions default to true.
touches_resourceslist(atom)A list of resources that the action may touch, used when building transactions.
accept:all | list(atom)The list of attributes to accept. Defaults to all attributes on the resource
delay_global_validations?booleanfalseIf true, global validations will be done in a before_action hook, regardless of their configuration on the resource.
skip_global_validations?booleanfalseIf true, global validations will be skipped. Useful for manual actions.
reject:all | list(atom)A list of attributes not to accept. If this is specified along with accept, these are removed from the accept list.
require_attributeslist(atom)A list of attributes that would normally allow_nil?, to require for this action. No need to include attributes that already do not allow nil?
error_handlermfaSets the error handler on the changeset. See Ash.Changeset.handle_errors/2 for more
manual?booleanInstructs Ash to skip the actual update/create/destroy step at the data layer. See the manual actions guide for more.

actions.destroy.change

change change

A change to be applied to the changeset.

See Ash.Resource.Change for more.

Examples

change relate_actor(:reporter)
change {MyCustomChange, :foo}

Arguments

NameTypeDefaultDocs
change(any, any -> any) | moduleThe module and options for a change. Also accepts a function that takes the changeset and the context. See Ash.Resource.Change.Builtins for builtin changes.

Options

NameTypeDefaultDocs
only_when_valid?booleanfalseIf the change should only be run on valid changes. By default, all changes are run unless stated otherwise here.
descriptionString.tAn optional description for the change
wherelist((any -> any) | module)[]Validations that should pass in order for this validation to apply. These validations failing will result in this validation being ignored.
always_atomic?booleanfalseBy default, changes are only run atomically if all changes will be run atomically or if there is no change/3 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Change

actions.destroy.validate

validate validation

Declares a validation to be applied to the changeset.

See Ash.Resource.Validation for more.

Examples

validate changing(:email)

Arguments

NameTypeDefaultDocs
validation(any -> any) | moduleThe module (or module and opts) that implements the Ash.Resource.Validation behaviour. Also accepts a one argument function that takes the changeset.

Options

NameTypeDefaultDocs
where(any -> any) | module | list((any -> any) | module)[]Validations that should pass in order for this validation to apply. Any of these validations failing will result in this validation being ignored.
only_when_valid?booleanfalseIf the validation should only run on valid changes. Useful for expensive validations or validations that depend on valid data.
messageString.tIf provided, overrides any message set by the validation error
descriptionString.tAn optional description for the validation
before_action?booleanfalseIf set to true, the validation will be run in a before_action hook
always_atomic?booleanfalseBy default, validations are only run atomically if all changes will be run atomically or if there is no validate/2 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Validation

actions.destroy.metadata

metadata name, type

A special kind of attribute that is only added to specific actions. Nothing sets this value, it must be set in a custom change after_action hook via Ash.Resource.put_metadata/3.

Examples

metadata :api_token, :string, allow_nil?: false
metadata :operation_id, :string, allow_nil?: false

Arguments

NameTypeDefaultDocs
nameatomThe name of the metadata
typeanyThe type of the metadata. See Ash.Type for more.

Options

NameTypeDefaultDocs
constraintsKeyword.t[]Type constraints on the metadata
descriptionString.tAn optional description for the metadata.
allow_nil?booleantrueWhether or not the metadata may return nil
defaultanyThe default value for the metadata to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Metadata

actions.destroy.argument

argument name, type

Declares an argument on the action

Examples

argument :password_confirmation, :string

Arguments

NameTypeDefaultDocs
nameatomThe name of the argument
typemoduleThe type of the argument. See Ash.Type for more.

Options

NameTypeDefaultDocs
descriptionString.tAn optional description for the argument.
constraintsKeyword.t[]Constraints to provide to the type when casting the value. For more information, see the constraints topic.
allow_nil?booleantrueWhether or not the argument value may be nil (or may be not provided). If nil value is given error is raised.
private?booleanfalseWhether or not the argument should be suppliable by the client.
sensitive?booleanfalseWhether or not the argument value contains sensitive information, like PII. See the security guide for more.
defaultanyThe default value for the argument to take. It can be a zero argument function e.g &MyMod.my_fun/0 or a value

Introspection

Target: Ash.Resource.Actions.Argument

Introspection

Target: Ash.Resource.Actions.Destroy

code_interface

Functions that will be defined on the Api module to interact with this resource. See the code interface guide for more.

Nested DSLs

Examples

code_interface do
  define_for MyApp.Api
  define :create_user, action: :create
  define :get_user_by_id, action: :get_by_id, args: [:id], get?: true
end

Options

NameTypeDefaultDocs
define_formodulefalseDefines the code interface on the resource module directly, using the provided Api.

code_interface.define

define name

Defines a function with the corresponding name and arguments. See the code interface guide for more.

Examples

define :get_user_by_id, action: :get_by_id, args: [:id], get?: true

Arguments

NameTypeDefaultDocs
nameatomThe name of the function that will be defined

Options

NameTypeDefaultDocs
actionatomThe name of the action that will be called. Defaults to the same name as the function.
argslist(atom | {:optional, atom})Map specific arguments to named inputs. Can provide any argument/attributes that the action allows.
not_found_error?booleantrueIf the action or interface is configured with get?: true, this determines whether or not an error is raised or nil is returned.
get?booleanExpects to only receive a single result from a read action, and returns a single result instead of a list. Ignored for other action types.
get_byatom | list(atom)Takes a list of fields and adds those fields as arguments, which will then be used to filter. Sets get? to true automatically. Ignored for non-read actions.
get_by_identityatomOnly relevant for read actions. Takes an identity, and gets its field list, performing the same logic as get_by once it has the list of fields.

Introspection

Target: Ash.Resource.Interface

code_interface.define_calculation

define_calculation name

Defines a function with the corresponding name and arguments, that evaluates a calculation. Use :_record to take an instance of a record. See the code interface guide for more.

Examples

define_calculation :referral_link, args: [:id]
define_calculation :referral_link, args: [{:arg, :id}, {:ref, :id}]

Arguments

NameTypeDefaultDocs
nameatomThe name of the function that will be defined

Options

NameTypeDefaultDocs
calculationatomThe name of the calculation that will be evaluated. Defaults to the same name as the function.
argsany[]Supply field or argument values referenced by the calculation, in the form of :name, {:arg, :name} and/or {:ref, :name}. See the code interface guide for more.

Introspection

Target: Ash.Resource.CalculationInterface

resource

General resource configuration

Examples

resource do
  description "A description of this resource"
  base_filter [is_nil: :deleted_at]
end

Options

NameTypeDefaultDocs
descriptionString.tA human readable description of the resource, to be used in generated documentation
base_filteranyA filter statement to be applied to any queries on the resource
default_contextanyDefault context to apply to any queries/changesets generated for this resource.
trace_nameString.tThe name to use in traces. Defaults to the short_name stringified. See the monitoring guide for more.
short_nameatomA short identifier for the resource, which should be unique. See the monitoring guide for more.
plural_nameatomA pluralized version of the resource short_name. May be used by generators or automated tooling.
simple_notifierslist(module)A list of notifiers that require no DSL. Can be used to avoid compile time dependencies on notifiers
require_primary_key?booleantrueAllow the resource to be used without any primary key fields. Warning: this option is experimental, and should not be used unless you know what you're doing.

identities

Unique identifiers for the resource

Nested DSLs

Examples

identities do
  identity :full_name, [:first_name, :last_name]
  identity :email, [:email]
end

identities.identity

identity name, keys

Represents a unique constraint on the resource.

See the identities guide for more.

Examples

identity :name, [:name]
identity :full_name, [:first_name, :last_name]

Arguments

NameTypeDefaultDocs
nameatomThe name of the identity.
keysatom | list(atom)The names of the attributes that uniquely identify this resource.

Options

NameTypeDefaultDocs
eager_check_withmoduleValidates that the unique identity provided is unique at validation time, outside of any transactions, using the api module provided.
pre_check_withmoduleValidates that the unique identity provided is unique in a before_action hook.
descriptionString.tAn optional description for the identity
messageString.tAn error message to use when the unique identity would be violated
all_tenants?booleanfalseWhether or not this identity is unique across all tenants. If the resource is not multitenant, has no effect.

Introspection

Target: Ash.Resource.Identity

changes

Declare changes that occur on create/update/destroy actions against the resource

See Ash.Resource.Change for more.

Nested DSLs

Examples

changes do
  change {Mod, [foo: :bar]}
  change set_context(%{some: :context})
end

changes.change

change change

A change to be applied to the changeset.

See Ash.Resource.Change for more.

Examples

change relate_actor(:reporter)
change {MyCustomChange, :foo}

Arguments

NameTypeDefaultDocs
change(any, any -> any) | moduleThe module and options for a change. Also accepts a function that takes the changeset and the context. See Ash.Resource.Change.Builtins for builtin changes.

Options

NameTypeDefaultDocs
on:create | :update | :destroy | list(:create | :update | :destroy)[:create, :update]The action types the validation should run on. Destroy actions are omitted by default as most changes don't make sense for a destroy.
only_when_valid?booleanfalseIf the change should only be run on valid changes. By default, all changes are run unless stated otherwise here.
descriptionString.tAn optional description for the change
wherelist((any -> any) | module)[]Validations that should pass in order for this validation to apply. These validations failing will result in this validation being ignored.
always_atomic?booleanfalseBy default, changes are only run atomically if all changes will be run atomically or if there is no change/3 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Change

preparations

Declare preparations that occur on all read actions for a given resource

Nested DSLs

Examples

preparations do
  prepare {Mod, [foo: :bar]}
  prepare set_context(%{some: :context})
end

preparations.prepare

prepare preparation

Declares a preparation, which can be used to prepare a query for a read action.

Examples

prepare build(sort: [:foo, :bar])

Arguments

NameTypeDefaultDocs
preparation(any, any -> any) | moduleThe module and options for a preparation. Also accepts functions take the query and the context.

Introspection

Target: Ash.Resource.Preparation

validations

Declare validations prior to performing actions against the resource

Nested DSLs

Examples

validations do
  validate {Mod, [foo: :bar]}
  validate at_least_one_of_present([:first_name, :last_name])
end

validations.validate

validate validation

Declares a validation for creates and updates.

See Ash.Resource.Change for more.

Examples

validate {Mod, [foo: :bar]}
validate at_least_one_of_present([:first_name, :last_name])

Arguments

NameTypeDefaultDocs
validation(any -> any) | moduleThe module (or module and opts) that implements the Ash.Resource.Validation behaviour. Also accepts a one argument function that takes the changeset.

Options

NameTypeDefaultDocs
where(any -> any) | module | list((any -> any) | module)[]Validations that should pass in order for this validation to apply. Any of these validations failing will result in this validation being ignored.
on:create | :update | :destroy | list(:create | :update | :destroy)[:create, :update]The action types the validation should run on. Many validations don't make sense in the context of deletion, so by default it is not included.
only_when_valid?booleanfalseIf the validation should only run on valid changes. Useful for expensive validations or validations that depend on valid data.
messageString.tIf provided, overrides any message set by the validation error
descriptionString.tAn optional description for the validation
before_action?booleanfalseIf set to true, the validation will be run in a before_action hook
always_atomic?booleanfalseBy default, validations are only run atomically if all changes will be run atomically or if there is no validate/2 callback defined. Set this to true to run it atomically always.

Introspection

Target: Ash.Resource.Validation

aggregates

Declare named aggregates on the resource.

These are aggregates that can be loaded only by name using Ash.Query.load/2. They are also available as top level fields on the resource.

See the aggregates guide for more.

Nested DSLs

Examples

aggregates do
  count :assigned_ticket_count, :reported_tickets do
    filter [active: true]
  end
end

aggregates.count

count name, relationship_path

Declares a named count aggregate on the resource

Supports filter, but not sort (because that wouldn't affect the count)

See the aggregates guide for more.

Nested DSLs

Examples

count :assigned_ticket_count, :assigned_tickets do
  filter [active: true]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
uniq?booleanfalseWhether or not to count unique values only
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource
filterany[]A filter to apply to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.count.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.exists

exists name, relationship_path

Declares a named exists aggregate on the resource

Supports filter, but not sort (because that wouldn't affect if something exists)

See the aggregates guide for more.

Nested DSLs

Examples

exists :has_ticket, :assigned_tickets

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.exists.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.first

first name, relationship_path, field

Declares a named first aggregate on the resource

First aggregates return the first value of the related record that matches. Supports both filter and sort.

See the aggregates guide for more.

Nested DSLs

Examples

first :first_assigned_ticket_subject, :assigned_tickets, :subject do
  filter [active: true]
  sort [:subject]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
sortanyA sort to be applied to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.first.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.sum

sum name, relationship_path, field

Declares a named sum aggregate on the resource

Supports filter, but not sort (because that wouldn't affect the sum)

See the aggregates guide for more.

Nested DSLs

Examples

sum :assigned_ticket_price_sum, :assigned_tickets, :price do
  filter [active: true]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.sum.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.list

list name, relationship_path, field

Declares a named list aggregate on the resource.

A list aggregate selects the list of all values for the given field and relationship combination.

See the aggregates guide for more.

Nested DSLs

Examples

list :assigned_ticket_prices, :assigned_tickets, :price do
  filter [active: true]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
uniq?booleanfalseWhether or not to count unique values only
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
sortanyA sort to be applied to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.list.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.max

max name, relationship_path, field

Declares a named max aggregate on the resource

Supports filter, but not sort (because that wouldn't affect the max)

See the aggregates guide for more.

Nested DSLs

Examples

max :first_assigned_ticket_subject, :assigned_tickets, :severity do
  filter [active: true]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.max.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.min

min name, relationship_path, field

Declares a named min aggregate on the resource

Supports filter, but not sort (because that wouldn't affect the min)

See the aggregates guide for more.

Nested DSLs

Examples

min :first_assigned_ticket_subject, :assigned_tickets, :severity do
  filter [active: true]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.min.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.avg

avg name, relationship_path, field

Declares a named avg aggregate on the resource

Supports filter, but not sort (because that wouldn't affect the avg)

See the aggregates guide for more.

Nested DSLs

Examples

avg :assigned_ticket_price_sum, :assigned_tickets, :price do
  filter [active: true]
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource

Options

NameTypeDefaultDocs
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
filterany[]A filter to apply to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.avg.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

aggregates.custom

custom name, relationship_path, type

Declares a named custom aggregate on the resource

Supports filter and sort.

Custom aggregates provide an implementation which must implement data layer specific callbacks.

See the relevant data layer documentation and the aggregates guide for more.

Nested DSLs

Examples

custom :author_names, :authors, :string do
  implementation {StringAgg, delimiter: ","}
end

Arguments

NameTypeDefaultDocs
nameatomThe field to place the aggregate in
relationship_pathatom | list(atom)The relationship or relationship path to use for the aggregate
typemoduleThe type of the value returned by the aggregate

Options

NameTypeDefaultDocs
implementationmoduleThe module that implements the relevant data layer callbacks
kind:count | :first | :sum | :list | :avg | :max | :min | :exists | :custom | {:custom, module}The kind of the aggregate
read_actionatomThe read action to use when building the aggregate. Defaults to the primary read action. Keep in mind this action must not have any required arguments.
fieldatomThe field to aggregate. Defaults to the first field in the primary key of the resource
filterany[]A filter to apply to the aggregate
sortanyA sort to be applied to the aggregate
descriptionString.tAn optional description for the aggregate
defaultanyA default value to use in cases where nil would be used. Count defaults to 0.
private?booleanfalseWhether or not the aggregate will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql
filterable?boolean | :simple_equalitytrueWhether or not the aggregate should be usable in filters.
authorize?booleantrueWhether or not the aggregate query should authorize based on the target action, if the parent query is authorized. Requires filter checks on the target action.

aggregates.custom.join_filter

join_filter relationship_path, filter

Declares a join filter on an aggregate. See the aggregates guide for more.

Examples

join_filter [:comments, :author], expr(active == true)

Arguments

NameTypeDefaultDocs
relationship_pathatom | list(atom)The relationship path on which to apply the join filter
filteranyThe filter to apply. Can be an expression or a filter template.

Introspection

Target: Ash.Resource.Aggregate.JoinFilter

Introspection

Target: Ash.Resource.Aggregate

calculations

Declare named calculations on the resource.

These are calculations that can be loaded only by name using Ash.Query.load/2. They are also available as top level fields on the resource.

See the calculations guide for more.

Nested DSLs

Examples

calculations do
  calculate :full_name, :string, MyApp.MyResource.FullName
end

calculations.calculate

calculate name, type, calculation \\ nil

Declares a named calculation on the resource.

Takes a module that must adopt the Ash.Calculation behaviour. See that module for more information.

To ensure that the necessary fields are selected:

1.) Specifying the select option on a calculation in the resource. 2.) Define a select/2 callback in the calculation module 3.) Set always_select? on the attribute in question

See the calculations guide for more.

Nested DSLs

Examples

Ash.Calculation implementation example:

calculate :full_name, :string, {MyApp.FullName, keys: [:first_name, :last_name]}, select: [:first_name, :last_name]

expr/1 example:

calculate :full_name, :string, expr(first_name <> " " <> last_name)

Arguments

NameTypeDefaultDocs
nameatomThe field name to use for the calculation value
typeanyThe type of the calculation. See Ash.Type for more.
calculation(any, any -> any) | module |any``The module, {module, opts} or expr(...) to use for the calculation. Also accepts a function that takes a single record and produces the result.

Options

NameTypeDefaultDocs
constraintsKeyword.t[]Constraints to provide to the type. See Ash.Type for more.
descriptionString.tAn optional description for the calculation
private?booleanfalseWhether or not the calculation will appear in any interfaces created off of this resource, e.g AshJsonApi and AshGraphql See the security guide for more.
selectlist(atom)[]A list of fields to ensure selected if the calculation is used.
loadany[]A load statement to be applied if the calculation is used.
allow_nil?booleantrueWhether or not the calculation can return nil.
filterable?boolean | :simple_equalitytrueWhether or not the calculation should be usable in filters.

calculations.calculate.argument

argument name, type

An argument to be passed into the calculation's arguments map

See the calculations guide for more.

Examples

argument :params, :map do
  default %{}
end
argument :retries, :integer do
  allow_nil? false
end

Arguments

NameTypeDefaultDocs
nameatomThe name of the argument
typemoduleThe type of the argument. See Ash.Type for more.

Options

NameTypeDefaultDocs
default(-> any) | mfa | any()A default value to use for the argument if not provided
allow_nil?booleantrueWhether or not the argument value may be nil (or may be not provided)
allow_expr?booleanfalseAllow passing expressions as argument values. Expressions cannot be type validated.
constraintsKeyword.t[]Constraints to provide to the type when casting the value. See the type's documentation and Ash.Type for more.

Introspection

Target: Ash.Resource.Calculation.Argument

Introspection

Target: Ash.Resource.Calculation

multitenancy

Options for configuring the multitenancy behavior of a resource.

To specify a tenant, use Ash.Query.set_tenant/2 or Ash.Changeset.set_tenant/2 before passing it to an operation.

See the multitenancy guide

Examples

multitenancy do
  strategy :attribute
  attribute :organization_id
  global? true
end

Options

NameTypeDefaultDocs
strategy:context | :attribute:contextDetermine if multitenancy is performed with attribute filters or using data layer features.
attributeatomIf using the attribute strategy, the attribute to use, e.g org_id
global?booleanfalseWhether or not the data also exists outside of each tenant.
parse_attributemfa{Ash.Resource.Dsl, :identity, []}An mfa ({module, function, args}) pointing to a function that takes a tenant and returns the attribute value