Rails 3 json custom json formatting

I have a collection of @clients with id and email attributes I want to make this json format

 [ 
 {"id":" 1","label":"johndoe@yahoo.com","value":"1"},{"id":"  2","label":"paulsmith@gmail.com.com","value":"2"}
]

in client_controller I defined the following method

def search
    @clients = Client.where(:user_id => current_user.id).select('id','email')
    render :partial => "clients/search"
  end

and here is the view of _search.json.erb

[ 
 <%= raw @client.map{|client| '{"id":"' +" #{client.id}" +'","label":"' + "#{client.email}" +  '","value":"' +"#{client.id}" +'"}' }.join(",") %>
]

this works, but I found it fugly ... is there a more elegant way to create a custom json format in a view?

+3
source share
4 answers

Use the helper function that you call from the view to format the output or library function that you call from the controller. Example (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
  end
end

private
def 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_json
end
+8
source

You just need to use the to_json method. In your case, this is

@client.to_json(:only => [:id, :label, :value])
+6
source

jBuilder gem GitHub

clients_controller

def search
    @clients = Client.where(:user_id => current_user.id)
end

search.json.jbuilder

json.id @clients.id
json.label @clients.email
json.value @clients.id

Jbuilder RailsCast

+1

You can use https://github.com/dewski/json_builder/ to customize the json response in the view and separate it from the controller. This is good when you need to add some attributes of the "current user", such as

[{:attending => event.attending?(current_user)}]
0
source

Source: https://habr.com/ru/post/1786343/


All Articles