ruby on rails - How to exclude some objects from as_json result -
i have model people
. model has method hide()
. in controller need return list of not hidden models in addiction external conditions.
# controller ... def index render json: people.all.as_json end
i thought, can place needed contidion overrided as_json
method, don't know how exclude hidden models resulting array.
i override as_json
method in people
model:
class people def as_json(options) return false if hidden() super(options) end def hidden?() ... # return true or false end ...
then call as_json
peoples
array:
peoples.aj_json
and get:
[ false, false, {...}, # model 1 {...}, # model 2 ]
but need array
[ {...}, # model 1 {...} # model 2 ]
is way as_json
? or must create flag, called hidden_flag
in model people
, filter models when make request db?
# controller ... def index peoples = people.where(hidden_flag: false) render json: peoples.as_json end
that's strange thing you're doing.
you have as_json
defined on people
model (which bad naming, "people" plural , model names should singular), , override return false
. so, when call as_json
on array of people
objects, makes sense returns false
each element of array.
if need empty array in case, can use clear method remove elements:
peoples.as_json.clear
but looks have serious flaws in logic if have this.
after main post edit:
a blunt approach return nil
instead of return false
, , use compact method rid of nil
values.
but, better way use active model serializers. here's a article rationalising use.
Comments
Post a Comment