0

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
vovan
  • 1,460
  • 12
  • 22

1 Answers1

1

That's a very strange thing you're doing.

You have as_json defined on the People model (which is bad naming, "people" is plural and model names should be singular), and you override it to return false. So, when you call as_json on an array of People objects, it makes sense that it returns false for each element of the array.

If you need to get an empty array in that case, you can use the clear method to remove all the elements:

peoples.as_json.clear

But it looks like you have some serious flaws in your logic if you have to do this.

After main post edit:

A blunt approach would be to return nil instead of return false, and then use the compact method to get rid of the nil values.

But, the better way to do this would be to use something like Active Model Serializers. Here's a good article rationalising its use.

p4sh4
  • 3,292
  • 1
  • 20
  • 33
  • sorry for my incomplete question. I have method hidden() in my People model. I planned to place condition in my as_json method that exclude hidden peoples from resulting array – vovan Jul 14 '15 at 05:00
  • Let's i fix my issue? – vovan Jul 14 '15 at 05:04
  • Now it's even more confusing. How about you edit your question to describe what you need to do at a higher level, and I'll take a look again. – p4sh4 Jul 14 '15 at 05:17
  • Can i define many output formats with ActiveModel::Serializer? For example: `render json: @people, :minimal` or `render json: @people, :full` – vovan Jul 14 '15 at 07:47
  • 1
    Yes, by using several serializers. Take a look at the second answer to [this question](http://stackoverflow.com/questions/12485404/how-to-implement-multiple-different-serializers-for-same-model-using-activemodel). – p4sh4 Jul 14 '15 at 09:07