Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

db: add support for custom through models in many-to-many fields #282

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

miry
Copy link

@miry miry commented Jan 11, 2025

This update allows specifying a custom class for the through option in many-to-many relationships, providing greater flexibility in defining intermediate models.

Example:

class Post < Marten::Model
  # Other fields...

  field :tags, :many_to_many, to: Tag, through: CustomPostTags
end

This makes it easier to define and manage custom behavior or attributes within the intermediary model.

Reference: #13

@@ -120,8 +122,8 @@ module Marten
register_field(
{{ @type }}.new(
{{ field_id.stringify }},
{% unless kwargs.is_a?(NilLiteral) %}**{{ kwargs }}{% end %},
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is not related to the main topic, but I think comma should be present inside the block. It worked because kwargs is not nil, because to is required.

@miry miry force-pushed the 13-many-to-many-through-model branch from ede43cd to 1285a53 Compare January 11, 2025 15:13
)
end
{% unless kwargs[:through] %}
class ::{{ through_model_name.id }} < Marten::DB::Model
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I could actually check if the class resolved and then create dynamic one if it is not defined.

@miry miry force-pushed the 13-many-to-many-through-model branch from 1285a53 to d7f2887 Compare January 11, 2025 15:17
@miry miry marked this pull request as ready for review January 11, 2025 15:18
This update allows specifying a custom class for the `through` option in many-to-many relationships,
providing greater flexibility in defining intermediate models.

Example:

```crystal
class Post < Marten::Model
  # Other fields...

  field :tags, :many_to_many, to: Tag, through: CustomPostTags
end
```

This makes it easier to define and manage custom behavior or attributes within the intermediary model.
@miry miry force-pushed the 13-many-to-many-through-model branch from d7f2887 to 57f422b Compare January 12, 2025 11:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant