Reputation: 7862
In my rails project I have model :
class Panel < ActiveRecord::Base
has_many :surveys
scope :by_survey_name, ->(survey_name) {
joins(:surveys).where('surveys.survey_name LIKE (?)', "%#{survey_name}%")
}
end
And the question is how can I use this scope in activeadmin fiter?
Upvotes: 5
Views: 4422
Reputation: 25054
Scopes need to be enabled explicitly: https://activerecord-hackery.github.io/ransack/going-further/other-notes/#using-scopesclass-methods
A string filter expects multiple scopes, such as contains
, equals
, starts_with
, ends_with
.
class Panel < ActiveRecord::Base
has_many :surveys
scope :survey_name_contains, ->(survey_name) {
joins(:surveys).where('surveys.survey_name LIKE (?)', "%#{survey_name}%")
}
scope :survey_name_equals, ...
scope :survey_name_starts_with, ...
scope :survey_name_ends_with, ...
def self.ransackable_scopes(_auth_object = nil)
[:by_survey_name, :survey_name_equals, :survey_name_starts_with, :survey_name_ends_with]
end
end
ActiveAdmin.register Panel do
filter :survey_name, as: :string
end
Alternatively, you can name the filer survey_name_in
:
class Panel < ActiveRecord::Base
has_many :surveys
scope :survey_name_in, ->(survey_name) {
joins(:surveys).where('surveys.survey_name LIKE (?)', "%#{survey_name}%")
}
def self.ransackable_scopes(_auth_object = nil)
[:survey_name_in]
end
end
ActiveAdmin.register Panel do
filter :survey_name_in, as: :string, label: 'Survey name'
end
Verified on activeadmin 2.13
and rails 7.0
.
Upvotes: 0
Reputation: 7862
Add to model:
def self.ransackable_scopes(_auth_object = nil)
[:by_survey_name]
end
and then in resource:
filter :by_survey_name, as: :string
Upvotes: 12