0

I am trying to do everything on a single page. The page is called users/index.html.erb.

On this page I return a simple data base query in json format.

I would like to also return a seperate query in non json format from the same database.

I'm trying to avoid partials for the moment as they make variable handling a bit more complicated that I want for my beginner level.

This is what I have:

class UsersController < ApplicationController


def index
     @users = User.including_relationships
     @followas= User.find_by name: params[:name]
     respond_to do |format|
     format.html # index.html.erb
     format.json {  render json: @users } 
     end
end
end

but it doesnt work unsurprisingly. How can I get it to work in one action?

Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125

1 Answers1

0

Not sure about your purpose of returning two formats of query from a single controller call. It usually happens when you use Javascript heavily (eg. Angular.js). Controller first returns the HTML page including all the HTML template and javascript, then data in JSON is returned in the second round.

So in your users/index.html.erb, you might have something like:

<p ng-repeat='user in users'>{{user.name}}</p>
<script>
  // do a AJAX call to retrieve users in JSON format
</script>

Then you will call users/index.json again to retrieve users information in JSON.

In short, your users/index is called twice, once for html, once for JSON.

It might seem unwise to call the same controller method twice just to render different format. In such case, you might consider to embed the JSON data in HTML. In such way, you will only render users/index.html.erb once and parse the data in JSON through Javascript on the client side.

Community
  • 1
  • 1
Yen-Ju
  • 467
  • 2
  • 6