简体   繁体   中英

Include a concern module in a rails controller

Here is my concern file: controllerconcerns.rb

require 'active_support/concern'

module Query_scopes
  extend ActiveSupport::Concern
  has_scope :title
end

Here is my controller I want to include it in: api_controller.rb

class ApiController < ApplicationController
  require 'concerns/controllerconcerns'
  include Query_scopes
  etc etc etc

Here is the error I'm getting:

undefined method `has_scope' for Query_scopes:Module

I have the has_scope gem installed and it works fine if I just say 'has_scope: scopename' within each individual controller I want it applied to... so how can I apply a few lines of 'has_scope' code to all my controllers?

You should follow the naming convention for using concerns, and also include what you want in the included do block :)

eg.

module QueryScopes
  extend ActiveSupport::Concern

   included do
     has_scope :title
   end
end

and then:

class ApiController < ApplicationController
  include QueryScopes
end

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