Rails 3 simultaneously rendering response of more than one action of a controller in another controller's view

258 Views Asked by At

Using Rails v 3.0.11, Ruby v 1.9.3

I have a page having link "Reports" on it, clicking on which invokes ReportsController#index

class ReportsController < ApplicationController
  def index
    # Renders index.html.haml
  end
end

Now I have an already existing JSON API (ReportsDataController shown below) returning JSON response which I need to reuse.

A Controller returning JSON response (my JSON API)

class ReportsDataController < ApplicationController

  respond_to :json

  def users_events_activity
    user_activity_data_obj = find_user_events_activity_per_day
    respond_with user_activity_data_obj
  end

  def users_comments_activity
    user_comments_data_obj = find_user_comments_activity_per_day
    respond_with user_comments_data_obj
  end

end

On my app/views/reports/index.html.haml I need to simultaneously render the data returned by actions ReportsDataController#users_events_activity and ReportsDataController#users_comments_activity.

Is there a Rails standard way by which the above mentioned requirement can be achieved? If not can anybody please suggest me some approaches to achieve the same?

Thanks,

Jignesh

1

There are 1 best solutions below

2
On

If you don't want to make two requests, you can always create another controller action and render the JSON like this:

class ReportsDataController < ApplicationController

  respond_to :json

  def users_combined_events_comments_activity
    user_activity_data_obj = find_user_events_activity_per_day
    user_comments_data_obj = find_user_comments_activity_per_day
    respond_with { activities: user_activity_data_obj, comments: user_comments_data_obj }
  end
end