开发者

rails 3 json custom json formatting

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

 [ 
 {"id":" 1","label":"johndoe@yahoo.com","value":"1"},{"id":"  2","label":"paulsmith@gmail.com.com","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?开发者_运维知识库


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


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

For more info you can visit Jbuilder on RailsCast


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)}]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜