rails 3 json custom json formatting
Use a helper function you call from the view to format the output or a library function you call from the controller. Example (of later):
def search @clients = Client.where(:user_id => current_user.id).select('id','email') respond_to do |format| format.html format.json do render :json => custom_json_for(@clients) end endendprivatedef custom_json_for(value) list = value.map do |client| { :id => " #{client.id}", :label => client.email.to_s, :value => client.id.to_s } end list.to_jsonend
You just need use the to_json method. In you case it's
@client.to_json(:only => [:id, :label, :value])
You could use jBuilder gem from GitHub
for clients_controller
def search @clients = Client.where(:user_id => current_user.id)end
and search.json.jbuilder
json.id @clients.idjson.label @clients.emailjson.value @clients.id
For more info you can visit Jbuilder on RailsCast