简体   繁体   中英

How to include Concern inside Initializer with nesting on Rails 5 app

In a nutshell, I'm attempting to pass form values corresponding to attributes on the version model (provided by paper_trail gem) to a controller that's invoking a custom method, which performs an optimized search. But, I'm receiving a NoMethodError. The method works as intended when declared inside the initializer itself, but not elsewhere. Any thoughts on how to fix?

Code is below - I've omitted portions that didn't seem relevant:

app/controllers/worker/csr_activities_controller.rb

class Worker::CustomerSupportActivitiesController < Worker::BaseController  
  def index
    PaperTrail::Version.search_versions(resource_params)
  end

  ...

  private 
    def resource_params
      params.fetch(:query).permit(:whodunnit, :event, :item_type, :term, :start_date, :end_date)
    end
end

app/controllers/concerns/search_versions.rb

module SearchVersions
  extend ActiveSupport::Concern

  def search_versions(params)
    ...
  end 
end 

config/initializers/paper_trail.rb

PaperTrail.config.track_associations = false
PaperTrail.config.version_limit = 100

require Rails.root.join('./app/controllers/concerns/search_versions.rb')

module PaperTrail
  class Version < ActiveRecord::Base    
    include SearchVersions
  end
end

terminal

...
[51e4ee33-6308-4861-bf3a-e1c51ecdfac0] NoMethodError (undefined method `search_versions' for #<Class:0x007f94e5ed2a70>):
...

Classic - figured it out shortly after posting here. The issue can be fixed by changing:

include SearchVersions to extend SearchVersions inside config/initializers/paper_trail.rb .

Essentially, I need to use extend since I'm invoking the method on the Class Version which has been extended by the Module SearchVersions.

Edit: changed terminology based on engineersmnky's comment to prevent confusion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM