Skip to content

Commit

Permalink
hasMany collection columns (thoughtbot#2415)
Browse files Browse the repository at this point in the history
  • Loading branch information
jubilee2 authored Oct 18, 2023
1 parent 84badf2 commit 21c5288
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 2 deletions.
3 changes: 3 additions & 0 deletions docs/customizing_dashboards.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ association `belongs_to :country`, from your model.

**Field::HasMany**

`:collection_attributes` - Set the columns to display in the show view.
Default is COLLECTION_ATTRIBUTES in dashboard.

`:limit` - The number of resources (paginated) to display in the show view. To disable pagination,
set this to `0` or `false`. Default is `5`.

Expand Down
6 changes: 5 additions & 1 deletion lib/administrate/field/has_many.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ def self.permitted_attribute(attr, _options = {})
end

def associated_collection(order = self.order)
Administrate::Page::Collection.new(associated_dashboard, order: order)
Administrate::Page::Collection.new(
associated_dashboard,
order: order,
collection_attributes: options[:collection_attributes],
)
end

def attribute_key
Expand Down
1 change: 1 addition & 0 deletions lib/administrate/page/collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module Administrate
module Page
class Collection < Page::Base
def attribute_names
options.fetch(:collection_attributes, nil) ||
dashboard.collection_attributes
end

Expand Down
4 changes: 3 additions & 1 deletion spec/example_app/app/dashboards/order_dashboard.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ class OrderDashboard < Administrate::BaseDashboard
address_state: Field::String,
address_zip: Field::String,
customer: Field::BelongsTo.with_options(order: "name"),
line_items: Field::HasMany,
line_items: Field::HasMany.with_options(
collection_attributes: %i[product quantity unit_price total_price],
),
total_price: Field::Number.with_options(prefix: "$", decimals: 2),
shipped_at: Field::DateTime,
payments: Field::HasMany,
Expand Down
15 changes: 15 additions & 0 deletions spec/features/show_page_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,21 @@
end
end

it "displays specified collection_attributes for the has_many association" do
line_item = create(:line_item)

visit admin_order_path(line_item.order)

within(table_for_attribute(:line_items)) do
columns = all("tr th").map do |e|
e[:class]&.split&.last&.split("--line_item_")&.last
end
expect(%w[product quantity unit_price total_price]).to(
eq(columns.first(4)),
)
end
end

def ids_in_table
all("tr td:first-child").map(&:text).map(&:to_i)
end
Expand Down

0 comments on commit 21c5288

Please sign in to comment.