Passing parameters to the as_json method

Asked

Viewed 640 times

4

I am trying to pass parameters to the as_json method (overwriting the method) in my model. Because only with the date that comes from the user can I return my result. According to this past date I add a field to the return json. We can call "new value" the value to be inserted to the final json;

My question is how to update json and whether this way of passing the parameters in render :json... is correct.

Development environment:

  • Rails 4
  • Ruby 2.0.0

Inside my api controller:

 render :json => @schedules.as_json({:date => params[:date]})

In my model

def as_json(options={})
  if options.has_key?(:date)
    # obtém novo valor
    # adiciona novo_valor ao json de retorno
  end
  # Deve manter o comportamento do as_json, que penso ser só a chamada super(options). Pois ele deve continuar e chamar o método to_json, caso contrário recebo um erro.
end

1 answer

0


I was able to find the solution:

On my controller:

render :json => @schedules.as_json({:date => date})

In my model:

def as_json(options = nil)
  hash = super(options)

  if options.has_key?(:date)
    date = options[:date]
    hash.merge!({ :number_of_available_vacancies => number_of_available_vacancies(date)})
  end

  hash
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.