17
I am working on ruby on rails project and I want to add respond to Json.
One simple way is:--
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
format.json { render :json => @users.to_json }
end
end
But there are some issues with this:-
- I don't want to give the whole user object in json response like password hash and cache counter attributes. Facebook, twitter attributes etc.
- I want to add more details in the json object (considering stackoverflow model) like Latest question by each user, latest answer given by each user. Instead of image name stored in db via paperclip, I want to pass full url of the image.
So the question is how can code json reponse in index.json.erb file like we do in index.html.erb. Format your own json response as per needs.
EDIT
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
format.json { render :file => "index.json.erb", :content_type => 'application/json' }
end
end
index.json.erb file:-
<% @users.each do |user| %>
{
first_name: <%= user.first_name %>,
last_name: <%= user.last_name %>
}
<% end %>
Error:--
template missing.
PS:-- I am just trying using creating this file. This is just a sample
EDIT

edit
{ { first_name: Mohit , last_name: Jain } { first_name: Sahil Miglani, last_name: } { first_name: Hitesh Bansal, last_name: } { first_name: Sudhanshu, last_name: } { first_name: Saakshi, last_name: } { first_name: Kutta, last_name: } { first_name: bc, last_nam