I have model People. Model has method hide(). In a controller a need return list of not hidden models in addiction from some external conditions.
# Controller
...
def index
render json: People.all.as_json
end
I thought, that i can place needed contidion to overrided as_json method, but i don't know how to exclude hidden models from 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 i call as_json for peoples array:
peoples.aj_json
and I get:
[
false,
false,
{...}, # model 1
{...}, # model 2
]
But I need get array
[
{...}, # model 1
{...} # model 2
]
Is any way to do this with as_json? Or i must create a flag, called hidden_flag in a model People and filter models when i make request to db?
# Controller
...
def index
peoples = People.where(hidden_flag: false)
render json: peoples.as_json
end