diff --git a/.github/workflows/codecheck.yml b/.github/workflows/codecheck.yml index 74e9f03..36e110f 100644 --- a/.github/workflows/codecheck.yml +++ b/.github/workflows/codecheck.yml @@ -10,9 +10,9 @@ jobs: codecheck: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - uses: ruby/setup-ruby@v1 with: - ruby-version: 2.7 + ruby-version: 3.3 bundler-cache: true - run: bundle exec rubocop \ No newline at end of file diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index bb6a602..d2bd3cc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,20 +11,35 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest] - ruby: [2.5, 2.6, 2.7] - runs-on: ${{ matrix.os }} + ruby: ['3.1', '3.2', '3.3', '3.4', '4.0'] + rails: ['6.1', '7.0'] + mongoid: ['7.5', '8.1'] + exclude: + # Rails 6.1 doesn't support Ruby 3.4 or later. + - ruby: '3.4' + rails: '6.1' + - ruby: '4.0' + rails: '6.1' + # ubuntu-latest (26.04) can't compile native extensions against Ruby 3.2's headers. + runs-on: ubuntu-24.04 + name: Ruby ${{ matrix.ruby }}, Rails ${{ matrix.rails }}, Mongoid ${{ matrix.mongoid }} + env: + RAILS_VERSION: ${{ matrix.rails }} + MONGOID_VERSION: ${{ matrix.mongoid }} services: mongodb: - image: mongo + image: mongo:7 ports: - 27017:27017 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} - bundler-cache: true + # Not setup-ruby's bundler-cache: it locks the Gemfile without this job's RAILS_VERSION and + # MONGOID_VERSION. setup-ruby still writes that default lockfile, and moving it to this job's + # versions can fail to resolve, so resolve from scratch. + - run: rm -f Gemfile.lock && bundle install - run: bundle exec rake diff --git a/.gitignore b/.gitignore index d51e3c7..4ba66d4 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ spec/reports /test_app/config/mongoid.yml /spec/rails .ruby-version +Gemfile.lock diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9242280 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +## 2.0.0 + +Supports Ruby 3.1+, Rails 6.1 and 7.0, Mongoid 7 and 8, and ActiveAdmin 2.x. Use 1.0.0 for older +versions. + +### Breaking changes + +* Requires Ruby 3.1 or later, Mongoid 7.0 or later, and ActiveAdmin 2.x. +* `build_new_resource` no longer passes `resource_params` to the build method. ActiveAdmin assigns + them right after building, so they were being assigned twice. + +### Fixes + +* Rails 7.0: the resource controller patch is applied in `to_prepare`, since Rails 7 doesn't autoload + during initialization. +* ActiveAdmin 2.14: CSV export no longer goes through `in_paginated_batches`, which needs + ActiveRecord. Like it, the export skips the query cache. +* Ruby 3: CSV options are passed as keyword arguments. +* Select filters search the key the document stores, so filters on `belongs_to` and + `has_and_belongs_to_many` associations work. +* `has_many` and `has_one` associations are no longer default filters, since their keys are in the + related documents. Declaring one explicitly raises an error that says so. +* The index page's "Displaying X - Y" counts the current page in the database instead of loading + documents (and no longer counts the whole collection). +* `primary_key` works for subclasses of a document. +* Declares the `csv` dependency, which Ruby 3.4 no longer installs by default. diff --git a/Gemfile b/Gemfile index 6de200c..692e83f 100644 --- a/Gemfile +++ b/Gemfile @@ -2,21 +2,20 @@ source 'https://rubygems.org' gemspec -gem 'ransack-mongoid', git: 'https://github.com/activerecord-hackery/ransack-mongoid' +# ransack-mongoid 0.x was never released to RubyGems. Pinned to the last commit that supports +# ransack 2.x, which ActiveAdmin 2 requires. +gem 'ransack-mongoid', git: 'https://github.com/riverock/ransack-mongoid', ref: 'f83ae55ea67fc0a0bca30158f3e04c49362f4464' -gem 'rails', '>= 5.2', '< 6.1' - -gem 'devise' - -gem 'pry-rails' +# CI picks the versions; see .github/workflows/tests.yml. +gem 'rails', "~> #{ENV.fetch('RAILS_VERSION', '7.0')}.0" +gem 'mongoid', "~> #{ENV.fetch('MONGOID_VERSION', '8.1')}.0" +gem 'devise', '~> 4.0' # ActiveAdmin 2 requires < 5 gem 'jquery-rails' gem 'jquery-ui-rails' -gem 'jslint' group :test do gem 'capybara' - gem 'poltergeist' gem 'launchy' gem 'simplecov', require: false end diff --git a/Gemfile.lock b/Gemfile.lock deleted file mode 100644 index f85a85e..0000000 --- a/Gemfile.lock +++ /dev/null @@ -1,304 +0,0 @@ -GIT - remote: https://github.com/activerecord-hackery/ransack-mongoid - revision: bd1935293d2f285fa7cf33d2c5c90d981bf67338 - specs: - ransack-mongoid (0.1.0) - -PATH - remote: . - specs: - activeadmin-mongoid (1.0.0) - activeadmin (>= 1.4.3) - jquery-rails - kaminari-mongoid - mongoid (>= 6.0, < 8.a) - sass-rails (>= 3.1.4) - -GEM - remote: https://rubygems.org/ - specs: - actioncable (5.2.3) - actionpack (= 5.2.3) - nio4r (~> 2.0) - websocket-driver (>= 0.6.1) - actionmailer (5.2.3) - actionpack (= 5.2.3) - actionview (= 5.2.3) - activejob (= 5.2.3) - mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 2.0) - actionpack (5.2.3) - actionview (= 5.2.3) - activesupport (= 5.2.3) - rack (~> 2.0) - rack-test (>= 0.6.3) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.0.2) - actionview (5.2.3) - activesupport (= 5.2.3) - builder (~> 3.1) - erubi (~> 1.4) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.0.3) - activeadmin (2.6.0) - arbre (~> 1.2, >= 1.2.1) - formtastic (~> 3.1) - formtastic_i18n (~> 0.4) - inherited_resources (~> 1.7) - jquery-rails (~> 4.2) - kaminari (~> 1.0, >= 1.0.1) - railties (>= 5.2, < 6.1) - ransack (~> 2.1, >= 2.1.1) - sassc-rails (~> 2.1) - sprockets (>= 3.0, < 4.1) - activejob (5.2.3) - activesupport (= 5.2.3) - globalid (>= 0.3.6) - activemodel (5.2.3) - activesupport (= 5.2.3) - activerecord (5.2.3) - activemodel (= 5.2.3) - activesupport (= 5.2.3) - arel (>= 9.0) - activestorage (5.2.3) - actionpack (= 5.2.3) - activerecord (= 5.2.3) - marcel (~> 0.3.1) - activesupport (5.2.3) - concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (>= 0.7, < 2) - minitest (~> 5.1) - tzinfo (~> 1.1) - addressable (2.5.2) - public_suffix (>= 2.0.2, < 4.0) - arbre (1.2.1) - activesupport (>= 3.0.0) - arel (9.0.0) - ast (2.4.0) - bcrypt (3.1.13) - bson (4.7.1) - builder (3.2.4) - capybara (3.12.0) - addressable - mini_mime (>= 0.1.3) - nokogiri (~> 1.8) - rack (>= 1.6.0) - rack-test (>= 0.6.3) - regexp_parser (~> 1.2) - xpath (~> 3.2) - cliver (0.3.2) - coderay (1.1.2) - concurrent-ruby (1.1.6) - crass (1.0.6) - devise (4.7.1) - bcrypt (~> 3.0) - orm_adapter (~> 0.1) - railties (>= 4.1.0) - responders - warden (~> 1.2.3) - diff-lcs (1.3) - docile (1.3.1) - erubi (1.9.0) - ffi (1.12.1) - formtastic (3.1.5) - actionpack (>= 3.2.13) - formtastic_i18n (0.6.0) - globalid (0.4.2) - activesupport (>= 4.2.0) - has_scope (0.7.2) - actionpack (>= 4.1) - activesupport (>= 4.1) - i18n (1.8.2) - concurrent-ruby (~> 1.0) - inherited_resources (1.11.0) - actionpack (>= 5.0, < 6.1) - has_scope (~> 0.6) - railties (>= 5.0, < 6.1) - responders (>= 2, < 4) - jaro_winkler (1.5.4) - jquery-rails (4.3.3) - rails-dom-testing (>= 1, < 3) - railties (>= 4.2.0) - thor (>= 0.14, < 2.0) - jquery-ui-rails (6.0.1) - railties (>= 3.2.16) - jslint (1.2.0) - json - json (2.3.1) - kaminari (1.2.1) - activesupport (>= 4.1.0) - kaminari-actionview (= 1.2.1) - kaminari-activerecord (= 1.2.1) - kaminari-core (= 1.2.1) - kaminari-actionview (1.2.1) - actionview - kaminari-core (= 1.2.1) - kaminari-activerecord (1.2.1) - activerecord - kaminari-core (= 1.2.1) - kaminari-core (1.2.1) - kaminari-mongoid (1.0.1) - kaminari-core (~> 1.0) - mongoid - launchy (2.4.3) - addressable (~> 2.3) - loofah (2.5.0) - crass (~> 1.0.2) - nokogiri (>= 1.5.9) - mail (2.7.1) - mini_mime (>= 0.1.1) - marcel (0.3.3) - mimemagic (~> 0.3.2) - method_source (0.9.2) - mimemagic (0.3.10) - nokogiri (~> 1) - rake - mini_mime (1.0.1) - mini_portile2 (2.4.0) - minitest (5.14.1) - mongo (2.11.3) - bson (>= 4.4.2, < 5.0.0) - mongoid (7.0.5) - activemodel (>= 5.1, < 6.1) - mongo (>= 2.5.1, < 3.0.0) - nio4r (2.3.1) - nokogiri (1.10.9) - mini_portile2 (~> 2.4.0) - orm_adapter (0.5.0) - parallel (1.19.1) - parser (2.7.0.2) - ast (~> 2.4.0) - poltergeist (1.18.1) - capybara (>= 2.1, < 4) - cliver (~> 0.3.1) - websocket-driver (>= 0.2.0) - polyamorous (2.3.2) - activerecord (>= 5.2.1) - pry (0.12.2) - coderay (~> 1.1.0) - method_source (~> 0.9.0) - pry-rails (0.3.8) - pry (>= 0.10.4) - public_suffix (3.0.3) - rack (2.2.3) - rack-test (1.1.0) - rack (>= 1.0, < 3) - rails (5.2.3) - actioncable (= 5.2.3) - actionmailer (= 5.2.3) - actionpack (= 5.2.3) - actionview (= 5.2.3) - activejob (= 5.2.3) - activemodel (= 5.2.3) - activerecord (= 5.2.3) - activestorage (= 5.2.3) - activesupport (= 5.2.3) - bundler (>= 1.3.0) - railties (= 5.2.3) - sprockets-rails (>= 2.0.0) - rails-dom-testing (2.0.3) - activesupport (>= 4.2.0) - nokogiri (>= 1.6) - rails-html-sanitizer (1.3.0) - loofah (~> 2.3) - railties (5.2.3) - actionpack (= 5.2.3) - activesupport (= 5.2.3) - method_source - rake (>= 0.8.7) - thor (>= 0.19.0, < 2.0) - rainbow (3.0.0) - rake (12.3.3) - ransack (2.3.2) - activerecord (>= 5.2.1) - activesupport (>= 5.2.1) - i18n - polyamorous (= 2.3.2) - regexp_parser (1.3.0) - responders (2.4.1) - actionpack (>= 4.2.0, < 6.0) - railties (>= 4.2.0, < 6.0) - rexml (3.2.5) - rspec-core (3.8.0) - rspec-support (~> 3.8.0) - rspec-expectations (3.8.2) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-mocks (3.8.0) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-rails (3.8.1) - actionpack (>= 3.0) - activesupport (>= 3.0) - railties (>= 3.0) - rspec-core (~> 3.8.0) - rspec-expectations (~> 3.8.0) - rspec-mocks (~> 3.8.0) - rspec-support (~> 3.8.0) - rspec-support (3.8.0) - rubocop (0.80.0) - jaro_winkler (~> 1.5.1) - parallel (~> 1.10) - parser (>= 2.7.0.1) - rainbow (>= 2.2.2, < 4.0) - rexml - ruby-progressbar (~> 1.7) - unicode-display_width (>= 1.4.0, < 1.7) - ruby-progressbar (1.10.1) - sass-rails (6.0.0) - sassc-rails (~> 2.1, >= 2.1.1) - sassc (2.2.1) - ffi (~> 1.9) - sassc-rails (2.1.2) - railties (>= 4.0.0) - sassc (>= 2.0) - sprockets (> 3.0) - sprockets-rails - tilt - simplecov (0.16.1) - docile (~> 1.1) - json (>= 1.8, < 3) - simplecov-html (~> 0.10.0) - simplecov-html (0.10.2) - sprockets (3.7.2) - concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (3.2.1) - actionpack (>= 4.0) - activesupport (>= 4.0) - sprockets (>= 3.0.0) - thor (0.20.3) - thread_safe (0.3.6) - tilt (2.0.10) - tzinfo (1.2.7) - thread_safe (~> 0.1) - unicode-display_width (1.6.1) - warden (1.2.8) - rack (>= 2.0.6) - websocket-driver (0.7.0) - websocket-extensions (>= 0.1.0) - websocket-extensions (0.1.5) - xpath (3.2.0) - nokogiri (~> 1.8) - -PLATFORMS - ruby - -DEPENDENCIES - activeadmin-mongoid! - capybara - devise - jquery-rails - jquery-ui-rails - jslint - launchy - poltergeist - pry-rails - rails (>= 5.2, < 6.1) - ransack-mongoid! - rspec-rails (~> 3.6) - rubocop (= 0.80.0) - simplecov - -BUNDLED WITH - 1.17.3 diff --git a/README.md b/README.md index 60feb35..5ffc540 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,19 @@ ActiveAdmin is holding off on pulling Mongoid support into the core ActiveAdmin application. This repo was pulled into the ActiveAdmin org from previous work done by Elia Schito, and will be maintained by Grzegorz Jakubiak, Nic Boie, JD Guzman, Elia Schito and other ActiveAdmin and community members. +### Requirements for version 2.0.0 +* Ruby 3.1 or greater (Ruby 3.4 and later need Rails 7.0). +* Rails 6.1 or 7.0 +* Mongoid 7.x or 8.x +* ActiveAdmin 2.x (tested on 2.14) +* `ransack-mongoid` - declare it in your Gemfile from GitHub; it has no RubyGems release that supports ransack 2.x or 3.x, which ActiveAdmin 2 requires: + + ```ruby + gem 'ransack-mongoid', github: 'riverock/ransack-mongoid', ref: 'f83ae55ea67fc0a0bca30158f3e04c49362f4464' + ``` + +See [CHANGELOG.md](CHANGELOG.md) for the changes from 1.0.0. + ### Requirements for version 1.0.0 * Ruby 2.4.0 or greater. * Tested working on Rails 5.2.3 @@ -39,8 +52,8 @@ For more on Mongoid support in ActiveAdmin see [this issue](https://github.com/g Add the following gems to your application's Gemfile, and lock the version: ```ruby -gem 'activeadmin-mongoid', '1.0.0' -gem 'ransack-mongoid', github: 'activerecord-hackery/ransack-mongoid' +gem 'activeadmin-mongoid', '~> 2.0' +gem 'ransack-mongoid', github: 'riverock/ransack-mongoid', ref: 'f83ae55ea67fc0a0bca30158f3e04c49362f4464' ``` You can safely remove the following lines, since are already activeadmin-mongoid dependencies: diff --git a/activeadmin-mongoid.gemspec b/activeadmin-mongoid.gemspec index 9634269..b46f474 100644 --- a/activeadmin-mongoid.gemspec +++ b/activeadmin-mongoid.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |gem| gem.email = ['elia@schito.me'] gem.description = %q{ActiveAdmin hacks to support Mongoid (some ActiveAdmin features are disabled)} gem.summary = %q{ActiveAdmin hacks to support Mongoid} - gem.homepage = '' + gem.homepage = 'https://github.com/activeadmin/activeadmin-mongoid' gem.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } gem.files = `git ls-files`.split("\n") @@ -17,13 +17,14 @@ Gem::Specification.new do |gem| gem.version = ActiveAdmin::Mongoid::VERSION gem.license = 'MIT' - gem.required_ruby_version = '>= 2.4' + gem.required_ruby_version = '>= 3.1' - gem.add_runtime_dependency 'mongoid', '>= 6.0', '< 8.a' - gem.add_runtime_dependency 'activeadmin', '>= 1.4.3' + gem.add_runtime_dependency 'mongoid', '>= 7.0', '< 9' + gem.add_runtime_dependency 'activeadmin', '~> 2.0' + gem.add_runtime_dependency 'csv' # the CSV builder; no longer a default gem from Ruby 3.4 gem.add_runtime_dependency 'kaminari-mongoid' gem.add_runtime_dependency 'jquery-rails' gem.add_runtime_dependency 'sass-rails', ['>= 3.1.4'] - gem.add_development_dependency 'rspec-rails', '~> 3.6' + gem.add_development_dependency 'rspec-rails', '~> 6.1' end diff --git a/lib/active_admin/mongoid.rb b/lib/active_admin/mongoid.rb index 16e46df..fcf14c0 100644 --- a/lib/active_admin/mongoid.rb +++ b/lib/active_admin/mongoid.rb @@ -16,6 +16,7 @@ require 'active_admin/mongoid/association/relatable' require 'active_admin/mongoid/inputs/filters/check_boxes_input' +require 'active_admin/mongoid/inputs/filters/select_input' require 'active_admin/mongoid/filters/active_filter' require 'active_admin/mongoid/filters/resource_extension' require 'active_admin/mongoid/controllers/resource_controller' diff --git a/lib/active_admin/mongoid/association/relatable.rb b/lib/active_admin/mongoid/association/relatable.rb index 6f17a87..8186bf4 100644 --- a/lib/active_admin/mongoid/association/relatable.rb +++ b/lib/active_admin/mongoid/association/relatable.rb @@ -7,6 +7,12 @@ def embeds? [:embeds_one, :embeds_many].include?(macro) end + # Whether the association's key is stored in this document, so it can be filtered on. + # has_many and has_one keep theirs in the related document. + def key_stored_on_document? + [:belongs_to, :has_and_belongs_to_many].include?(macro) + end + def foreign_key return if embeds? foreign_key.to_sym rescue nil diff --git a/lib/active_admin/mongoid/controllers/resource_controller.rb b/lib/active_admin/mongoid/controllers/resource_controller.rb index 67a3d12..bf8c0f3 100644 --- a/lib/active_admin/mongoid/controllers/resource_controller.rb +++ b/lib/active_admin/mongoid/controllers/resource_controller.rb @@ -1,14 +1,14 @@ require 'active_admin/engine' -ActiveAdmin::Engine.module_eval do - initializer 'active_admin.mongoid.resource_controller' do - class ActiveAdmin::ResourceController - def build_new_resource - scoped_collection.send( - method_for_build, - *resource_params - ) - end +# to_prepare, not an initializer: ResourceController inherits from InheritedResources::Base, +# which lives in that gem's app/controllers and can't be autoloaded during initialization +# on Rails 7. +ActiveAdmin::Engine.config.to_prepare do + ActiveAdmin::ResourceController.class_eval do + # No params: ActiveAdmin assigns resource_params right after building, and passing them here + # too assigned relation attributes twice. + def build_new_resource + scoped_collection.send(method_for_build) end end end diff --git a/lib/active_admin/mongoid/csv_builder.rb b/lib/active_admin/mongoid/csv_builder.rb index 16fdcfd..c9da6bc 100644 --- a/lib/active_admin/mongoid/csv_builder.rb +++ b/lib/active_admin/mongoid/csv_builder.rb @@ -1,7 +1,6 @@ module ActiveAdmin class CSVBuilder def build(controller, csv) - @collection = controller.send :find_collection, except: :pagination columns = exec_columns controller.view_context options = ActiveAdmin.application.csv_options.merge self.options bom = options.delete :byte_order_mark @@ -11,13 +10,19 @@ def build(controller, csv) csv << bom if bom if column_names - csv << CSV.generate_line(columns.map { |c| encode c.name, options }, csv_options) + csv << CSV.generate_line(columns.map { |c| encode c.name, options }, **csv_options) end - (1..paginated_collection.total_pages).each do |page| - paginated_collection(page).each do |resource| - resource = controller.send :apply_decorator, resource - csv << CSV.generate_line(build_row(resource, columns, options), csv_options) + # Not ActiveAdmin's in_paginated_batches: it wraps the loop in ActiveRecord::Base.uncached, + # and ActiveRecord isn't loaded in a Mongoid app. Skip Mongo's query cache the same way, so a + # large export doesn't keep every page cached until the request ends. + query_cache = defined?(::Mongo::QueryCache) ? ::Mongo::QueryCache : ::Mongoid::QueryCache + query_cache.uncached do + (1..controller.send(:paginated_collection).total_pages).each do |page| + controller.send(:paginated_collection, page).each do |resource| + resource = controller.send :apply_decorator, resource + csv << CSV.generate_line(build_row(resource, columns, options), **csv_options) + end end end diff --git a/lib/active_admin/mongoid/document.rb b/lib/active_admin/mongoid/document.rb index 8f89f92..7dbbc19 100644 --- a/lib/active_admin/mongoid/document.rb +++ b/lib/active_admin/mongoid/document.rb @@ -27,16 +27,12 @@ def quote_column_name name end end - # CLASS METHODS - included do - unless respond_to? :primary_key - class << self - attr_accessor :primary_key - end + unless respond_to?(:primary_key) && respond_to?(:primary_key=) + class_attribute :primary_key, instance_writer: false end - self.primary_key ||= :id + self.primary_key = :id if primary_key.nil? def column_for_attribute(name) self.class.fields[name.to_sym] diff --git a/lib/active_admin/mongoid/filters/resource_extension.rb b/lib/active_admin/mongoid/filters/resource_extension.rb index ae5b0bf..5dcd447 100644 --- a/lib/active_admin/mongoid/filters/resource_extension.rb +++ b/lib/active_admin/mongoid/filters/resource_extension.rb @@ -3,8 +3,10 @@ module ActiveAdmin::Filters::ResourceExtension def default_association_filters if resource_class.respond_to?(:reflect_on_all_associations) - without_embedded = resource_class.reflect_on_all_associations.reject { |e| e.embeds? } - poly, not_poly = without_embedded.partition { |r| r.macro == :belongs_to && r.options[:polymorphic] } + # Only associations whose key this document stores can be filtered (not embedded ones, + # has_many or has_one). + filterable = resource_class.reflect_on_all_associations.select(&:key_stored_on_document?) + poly, not_poly = filterable.partition { |r| r.macro == :belongs_to && r.options[:polymorphic] } filters = poly.map(&:foreign_key) + not_poly.map(&:name) filters.map &:to_sym diff --git a/lib/active_admin/mongoid/helpers/collection.rb b/lib/active_admin/mongoid/helpers/collection.rb index 10e5fd8..09102ea 100644 --- a/lib/active_admin/mongoid/helpers/collection.rb +++ b/lib/active_admin/mongoid/helpers/collection.rb @@ -8,7 +8,9 @@ module Collection def collection_size(collection = nil) collection ||= self.collection if collection.is_a?(::Mongoid::Criteria) - collection.entries.count + # Count in the database instead of loading the documents. Mongoid's count ignores the + # criteria's skip and limit, so pass them to get the size of the current page. + collection.count(collection.options.slice(:skip, :limit)) else original_collection_size(collection) end diff --git a/lib/active_admin/mongoid/inputs/filters/select_input.rb b/lib/active_admin/mongoid/inputs/filters/select_input.rb new file mode 100644 index 0000000..7300b0c --- /dev/null +++ b/lib/active_admin/mongoid/inputs/filters/select_input.rb @@ -0,0 +1,21 @@ +require 'active_admin/inputs/filters/select_input' + +class ActiveAdmin::Inputs::Filters::SelectInput + # ActiveAdmin builds this from reflection.association_primary_key, which Mongoid associations + # don't have. Filter on the key the document stores instead (belongs_to and + # has_and_belongs_to_many). has_many and has_one keep their keys in the related documents, so + # a filter on them can't match anything. + def searchable_method_name + return method unless reflection + return reflection.key if reflection.key_stored_on_document? + + raise ArgumentError, "Can't filter #{@object.klass} by #{method}: Mongoid #{reflection.macro} " \ + "associations aren't stored in the document. Remove `filter :#{method}`." + end + + def input_name + return method if seems_searchable? + + searchable_method_name&.to_s + (multiple? ? '_in' : '_eq') + end +end diff --git a/lib/active_admin/mongoid/version.rb b/lib/active_admin/mongoid/version.rb index c67e774..7a3c100 100644 --- a/lib/active_admin/mongoid/version.rb +++ b/lib/active_admin/mongoid/version.rb @@ -1,5 +1,5 @@ module ActiveAdmin module Mongoid - VERSION = '1.0.0' + VERSION = '2.0.0' end end diff --git a/spec/features/smoke_spec.rb b/spec/features/smoke_spec.rb index 0c04ad2..7f6d030 100644 --- a/spec/features/smoke_spec.rb +++ b/spec/features/smoke_spec.rb @@ -180,6 +180,22 @@ end end + describe 'select on a has_and_belongs_to_many association' do + it 'selects by editor' do + Post.first.update!(editors: [other_user]) + + select other_email, from: 'Editors' + click_on 'Filter' + within '#index_table_posts' do + expect(page).to have_content('Quick Brown Fox') + end + + select email, from: 'Editors' + click_on 'Filter' + expect(page).to_not have_content('Quick Brown Fox') + end + end + describe 'check_boxes' do it 'checks by other_user' do check email @@ -311,8 +327,10 @@ end it "builds csv" do + expect(Mongo::QueryCache).to receive(:uncached).and_call_original visit '/admin/admin_users.csv' expect(page.status_code).to eq(200) or eq(304) + expect(page.body).to include(email, other_email) end end end diff --git a/spec/lib/active_admin/mongoid/filter_form_builder_spec.rb b/spec/lib/active_admin/mongoid/filter_form_builder_spec.rb index f900605..70e3660 100644 --- a/spec/lib/active_admin/mongoid/filter_form_builder_spec.rb +++ b/spec/lib/active_admin/mongoid/filter_form_builder_spec.rb @@ -2,7 +2,7 @@ describe ActiveAdmin::Filters::FormBuilder do describe '#default_input_type' do - let(:instance) { described_class.new({}, {}, {}, {}) } + let(:instance) { described_class.new('q', {}, {}, {}) } # object_name must be a String on Rails 6.1+ let(:column) { double(:column) } subject { instance.default_input_type(nil) } diff --git a/spec/lib/active_admin/mongoid/filters/resource_extension_spec.rb b/spec/lib/active_admin/mongoid/filters/resource_extension_spec.rb new file mode 100644 index 0000000..a47e7b3 --- /dev/null +++ b/spec/lib/active_admin/mongoid/filters/resource_extension_spec.rb @@ -0,0 +1,19 @@ +require 'spec_helper' + +describe ActiveAdmin::Filters::ResourceExtension do + def default_association_filters(klass) + ActiveAdmin.application.namespace(:admin).resource_for(klass).send(:default_association_filters) + end + + it 'includes associations whose key the document stores' do + expect(default_association_filters(Post)).to include(:admin_user, :other_user, :editors) + end + + it 'leaves out has_many associations, whose keys are in the related documents' do + expect(default_association_filters(AdminUser)).not_to include(:posts) + end + + it 'leaves out embedded associations' do + expect(default_association_filters(Post)).not_to include(:author) + end +end diff --git a/spec/support/capybara.rb b/spec/support/capybara.rb index f62bf7d..370d15f 100644 --- a/spec/support/capybara.rb +++ b/spec/support/capybara.rb @@ -1,3 +1 @@ require 'capybara/rails' -require 'capybara/poltergeist' -Capybara.javascript_driver = :poltergeist diff --git a/test_app/app/admin/admin_users.rb b/test_app/app/admin/admin_users.rb index 69ef56c..1d1c1ab 100644 --- a/test_app/app/admin/admin_users.rb +++ b/test_app/app/admin/admin_users.rb @@ -8,7 +8,6 @@ end filter :email - filter :posts form do |f| f.inputs "Admin Details" do diff --git a/test_app/app/admin/posts.rb b/test_app/app/admin/posts.rb index 0a46ffa..73f8ac3 100644 --- a/test_app/app/admin/posts.rb +++ b/test_app/app/admin/posts.rb @@ -9,6 +9,7 @@ filter :view_count, as: :numeric filter :admin_user, as: :select filter :other_user, as: :check_boxes + filter :editors, as: :select index do selectable_column diff --git a/test_app/app/assets/config/manifest.js b/test_app/app/assets/config/manifest.js new file mode 100644 index 0000000..e2c3235 --- /dev/null +++ b/test_app/app/assets/config/manifest.js @@ -0,0 +1 @@ +//= link active_admin.js diff --git a/test_app/app/models/post.rb b/test_app/app/models/post.rb index 57b9704..4322462 100644 --- a/test_app/app/models/post.rb +++ b/test_app/app/models/post.rb @@ -7,7 +7,9 @@ class Post field :view_count, type: ::Integer, default: 0 belongs_to :admin_user belongs_to :other_user, class_name: 'AdminUser' + has_and_belongs_to_many :editors, class_name: 'AdminUser', inverse_of: nil embeds_one :author field :'author.city.name' + end diff --git a/test_app/bin/rails b/test_app/bin/rails new file mode 100755 index 0000000..0739660 --- /dev/null +++ b/test_app/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/test_app/bin/rake b/test_app/bin/rake new file mode 100755 index 0000000..1724048 --- /dev/null +++ b/test_app/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/test_app/bin/setup b/test_app/bin/setup new file mode 100755 index 0000000..2e29ac1 --- /dev/null +++ b/test_app/bin/setup @@ -0,0 +1,25 @@ +#!/usr/bin/env ruby +require 'fileutils' + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to setup or update your development environment automatically. + # This script is idempotent, so that you can run it at anytime and get an expectable outcome. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/test_app/config/boot.rb b/test_app/config/boot.rb index 4f49bfb..c6cc703 100644 --- a/test_app/config/boot.rb +++ b/test_app/config/boot.rb @@ -1,6 +1,5 @@ -require 'rubygems' - -# Set up gems listed in the Gemfile. +# Rails 6.1 relies on concurrent-ruby to load Logger, which concurrent-ruby 1.3.5 stopped doing. +require 'logger' ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) -require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/test_app/config/environment.rb b/test_app/config/environment.rb index ad9dd14..426333b 100644 --- a/test_app/config/environment.rb +++ b/test_app/config/environment.rb @@ -1,5 +1,5 @@ -# Load the rails application -require File.expand_path('application', __dir__) +# Load the Rails application. +require_relative 'application' -# Initialize the rails application +# Initialize the Rails application. Rails.application.initialize! diff --git a/test_app/config/environments/development.rb b/test_app/config/environments/development.rb index 8afe863..91850be 100644 --- a/test_app/config/environments/development.rb +++ b/test_app/config/environments/development.rb @@ -27,4 +27,6 @@ # Expands the lines which load the assets config.assets.debug = true + + config.eager_load = false end diff --git a/test_app/config/environments/test.rb b/test_app/config/environments/test.rb index 589d8a1..74e1057 100644 --- a/test_app/config/environments/test.rb +++ b/test_app/config/environments/test.rb @@ -33,4 +33,6 @@ # Print deprecation notices to the stderr config.active_support.deprecation = :stderr + + config.eager_load = false end diff --git a/test_app/config/initializers/inflections.rb b/test_app/config/initializers/inflections.rb index 5d8d9be..ac033bf 100644 --- a/test_app/config/initializers/inflections.rb +++ b/test_app/config/initializers/inflections.rb @@ -1,15 +1,16 @@ # Be sure to restart your server when you modify this file. -# Add new inflection rules using the following format -# (all these examples are active by default): -# ActiveSupport::Inflector.inflections do |inflect| +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end -# + # These inflection rules are supported but not enabled by default: -# ActiveSupport::Inflector.inflections do |inflect| +# ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end diff --git a/test_app/config/mongoid.2.yml b/test_app/config/mongoid.2.yml deleted file mode 100644 index 8355f4c..0000000 --- a/test_app/config/mongoid.2.yml +++ /dev/null @@ -1,20 +0,0 @@ -development: - host: localhost - database: test_app_development - -test: - host: localhost - database: test_app_test - -# set these environment variables on your prod server -production: - host: <%= ENV['MONGOID_HOST'] %> - port: <%= ENV['MONGOID_PORT'] %> - username: <%= ENV['MONGOID_USERNAME'] %> - password: <%= ENV['MONGOID_PASSWORD'] %> - database: <%= ENV['MONGOID_DATABASE'] %> - # slaves: - # - host: slave1.local - # port: 27018 - # - host: slave2.local - # port: 27019 diff --git a/test_app/config/mongoid.3.yml b/test_app/config/mongoid.3.yml deleted file mode 100644 index dcd09db..0000000 --- a/test_app/config/mongoid.3.yml +++ /dev/null @@ -1,96 +0,0 @@ -test: - # Configure available database sessions. (required) - sessions: - # Defines the default session. (required) - default: - # Defines the name of the default database that Mongoid can connect to. - # (required). - database: activeadmin_mongoid_test - # Provides the hosts the default session can connect to. Must be an array - # of host:port pairs. (required) - hosts: - - localhost:27017 - options: - # Change whether the session persists in safe mode by default. - # (default: false) - # safe: false - - # Change the default consistency model to :eventual or :strong. - # :eventual will send reads to secondaries, :strong sends everything - # to master. (default: :eventual) - # consistency: :eventual - - # How many times Moped should attempt to retry an operation after - # failure. (default: 30) - # max_retries: 30 - - # The time in seconds that Moped should wait before retrying an - # operation on failure. (default: 1) - # retry_interval: 1 - # Configure Mongoid specific options. (optional) - options: &default_options - # Configuration for whether or not to allow access to fields that do - # not have a field definition on the model. (default: true) - # allow_dynamic_fields: true - allow_dynamic_fields: false - - # Enable the identity map, needed for eager loading. (default: false) - # identity_map_enabled: false - identity_map_enabled: true - - # Includes the root model name in json serialization. (default: false) - # include_root_in_json: false - - # Include the _type field in serializaion. (default: false) - # include_type_for_serialization: false - - # Preload all models in development, needed when models use - # inheritance. (default: false) - # preload_models: false - - # Protect id and type from mass assignment. (default: true) - # protect_sensitive_fields: true - - # Raise an error when performing a #find and the document is not found. - # (default: true) - # raise_not_found_error: true - - # Raise an error when defining a scope with the same name as an - # existing method. (default: false) - scope_overwrite_exception: true - - # Skip the database version check, used when connecting to a db without - # admin access. (default: false) - # skip_version_check: false - - # User Active Support's time zone in conversions. (default: true) - # use_activesupport_time_zone: true - - # Ensure all times are UTC in the app side. (default: false) - # use_utc: false - -# production: -# sessions: -# default: -# uri: <%= ENV['MONGOLAB_URI'] %> -# options: -# skip_version_check: true -# identity_map_enabled: true -# safe: true -# options: -# *default_options -# -# development: -# sessions: -# default: -# database: activeadmin_mongoid_development -# hosts: -# - localhost:27017 -# options: -# consistency: :strong -# # In the test environment we lower the retries and retry interval to -# # low amounts for fast failures. -# max_retries: 1 -# retry_interval: 0 -# options: -# *default_options diff --git a/test_app/config/mongoid.4.yml b/test_app/config/mongoid.4.yml deleted file mode 100644 index 4433c91..0000000 --- a/test_app/config/mongoid.4.yml +++ /dev/null @@ -1,87 +0,0 @@ -test: - # Configure available database sessions. (required) - sessions: - # Defines the default session. (required) - default: - # Defines the name of the default database that Mongoid can connect to. - # (required). - database: activeadmin_mongoid_test - # Provides the hosts the default session can connect to. Must be an array - # of host:port pairs. (required) - hosts: - - localhost:27017 - options: - # Change whether the session persists in safe mode by default. - # (default: false) - # safe: false - - # Change the default consistency model to :eventual or :strong. - # :eventual will send reads to secondaries, :strong sends everything - # to master. (default: :eventual) - # consistency: :eventual - - # How many times Moped should attempt to retry an operation after - # failure. (default: 30) - # max_retries: 30 - - # The time in seconds that Moped should wait before retrying an - # operation on failure. (default: 1) - # retry_interval: 1 - # Configure Mongoid specific options. (optional) - options: &default_options - # Includes the root model name in json serialization. (default: false) - # include_root_in_json: false - - # Include the _type field in serializaion. (default: false) - # include_type_for_serialization: false - - # Preload all models in development, needed when models use - # inheritance. (default: false) - # preload_models: false - - # Protect id and type from mass assignment. (default: true) - # protect_sensitive_fields: true - - # Raise an error when performing a #find and the document is not found. - # (default: true) - # raise_not_found_error: true - - # Raise an error when defining a scope with the same name as an - # existing method. (default: false) - scope_overwrite_exception: true - - # Skip the database version check, used when connecting to a db without - # admin access. (default: false) - # skip_version_check: false - - # User Active Support's time zone in conversions. (default: true) - # use_activesupport_time_zone: true - - # Ensure all times are UTC in the app side. (default: false) - # use_utc: false - -# production: -# sessions: -# default: -# uri: <%= ENV['MONGOLAB_URI'] %> -# options: -# skip_version_check: true -# identity_map_enabled: true -# safe: true -# options: -# *default_options -# -# development: -# sessions: -# default: -# database: activeadmin_mongoid_development -# hosts: -# - localhost:27017 -# options: -# consistency: :strong -# # In the test environment we lower the retries and retry interval to -# # low amounts for fast failures. -# max_retries: 1 -# retry_interval: 0 -# options: -# *default_options diff --git a/test_app/config/mongoid.5.yml b/test_app/config/mongoid.5.yml deleted file mode 100644 index 0ecd0c6..0000000 --- a/test_app/config/mongoid.5.yml +++ /dev/null @@ -1,7 +0,0 @@ -test: - clients: - default: - database: activeadmin_mongoid_test - hosts: - - localhost:27017 -#scope_overwrite_exception: true diff --git a/test_app/config/mongoid.6.yml b/test_app/config/mongoid.6.yml deleted file mode 100644 index 0ecd0c6..0000000 --- a/test_app/config/mongoid.6.yml +++ /dev/null @@ -1,7 +0,0 @@ -test: - clients: - default: - database: activeadmin_mongoid_test - hosts: - - localhost:27017 -#scope_overwrite_exception: true diff --git a/test_app/config/mongoid.7.yml b/test_app/config/mongoid.7.yml index e4a9498..2147dfd 100644 --- a/test_app/config/mongoid.7.yml +++ b/test_app/config/mongoid.7.yml @@ -3,12 +3,11 @@ development: default: database: activeadmin_mongoid_development hosts: - - localhost:27017 + - <%= ENV.fetch('MONGODB_HOST', 'localhost:27017') %> test: clients: default: database: activeadmin_mongoid_test hosts: - - localhost:27017 -#scope_overwrite_exception: true + - <%= ENV.fetch('MONGODB_HOST', 'localhost:27017') %> diff --git a/test_app/config/mongoid.8.yml b/test_app/config/mongoid.8.yml new file mode 100644 index 0000000..2147dfd --- /dev/null +++ b/test_app/config/mongoid.8.yml @@ -0,0 +1,13 @@ +development: + clients: + default: + database: activeadmin_mongoid_development + hosts: + - <%= ENV.fetch('MONGODB_HOST', 'localhost:27017') %> + +test: + clients: + default: + database: activeadmin_mongoid_test + hosts: + - <%= ENV.fetch('MONGODB_HOST', 'localhost:27017') %>