3

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

 [ 
 {"id":" 1","label":"[email protected]","value":"1"},{"id":"  2","label":"[email protected]","value":"2"}
]

in clients_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 _search.json.erb

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

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

0

4 Answers 4

8

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
  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
Sign up to request clarification or add additional context in comments.

1 Comment

For a more decoupled and scalable solution check out RABL templates.
6

You just need use the to_json method. In you case it's

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

2 Comments

this doesn't for the custom output format I need. I clarified my question, any other ideas?
@client.to_json(...) outputs standard json. Can you clarify what you mean by custom? If you mean change the whitespace, new lines, etc. then your solution is correct. However you shouldn't need to make a custom output for json otherwise your not talking about standardized json.
1

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.id
json.label @clients.email
json.value @clients.id

For more info you can visit Jbuilder on RailsCast

Comments

0

You can use https://github.com/dewski/json_builder/ to customize your json response in the view and separate it from the controller. It's good when you need to add some "current user" depending attributes like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.