Skip to content

Instantly share code, notes, and snippets.

@kuboon
Last active November 3, 2023 11:39
Show Gist options
  • Save kuboon/cc57c3372669320112abd9044771c1de to your computer and use it in GitHub Desktop.
Save kuboon/cc57c3372669320112abd9044771c1de to your computer and use it in GitHub Desktop.
# 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>
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
# 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
# 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