Last active
November 3, 2023 11:39
-
-
Save kuboon/cc57c3372669320112abd9044771c1de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# views/fields/belongs_to_scoped/_form.html.erb | |
<div class="field-unit__label"> | |
<%= f.label field.permitted_attribute %> | |
</div> | |
<div class="field-unit__field"> | |
<%= f.select(field.permitted_attribute) do %> | |
<%= options_for_select(field.associated_resource_options(f.object.send("#{field.name}_candidates")), field.selected_option) %> | |
<% end %> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BelongsToScoped < Administrate::Field::BelongsTo | |
def associated_resource_options(candidate_resources) | |
[nil] + candidate_resources.map do |resource| | |
[display_candidate_resource(resource), resource.send(primary_key)] | |
end | |
end | |
def to_partial_path | |
case page | |
when :form; "/fields/belongs_to_scoped/form" | |
else "/fields/belongs_to/#{page}" | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example | |
class User < ApplicationRecord | |
belongs_to :group | |
belongs_to :user | |
# this method is called in form/fields/belongs_to_scoped/_form | |
def user_candidates | |
group ? User.where(locale: group.locale) : User.all | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example | |
#... | |
ATTRIBUTE_TYPES = { | |
group: Field::BelongsTo, | |
user: BelongsToScoped | |
} | |
#... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment