Passing parameters to the as_json method

4

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

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

Development Environment:

  • Rails 4
  • Ruby 2.0.0

Inside my controller of my api:

 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
    
asked by anonymous 16.03.2014 / 07:02

1 answer

0

I was able to find the solution:

In 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
    
17.03.2014 / 14:06