-1

I would like to be able to render multiple Json renders in my controller. I have a rails Json API using the Model serializers gem. At the moment I can only render one object. What I would like to do is to also render the @news and @users but right now I'm only rendering the @articles.

Backend Articles controller.rb:

class ArticlesController < ApplicationController
impressionist :actions=>[:show]
  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.where(:is_published => true).order('created_at DESC').page(params[:page]).per(6)
    @news = Article.where(:news => true)
    @users = User.all

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @articles.all }
    end
  end
end

Backend Article Serializer:

class ArticleSerializer < ActiveModel::Serializer
  attributes :id, :title, :teaser_title, :content, :teaser_content, :category, :author, :published, :num_comments, :tags, :featured, :app, :news, :tech, :device, :game, :laptop, :image, :user_id, :is_published, :created_at, :updated_at, :impressionist_count, :previous_post, :next_post, :user_id
end

Frontend site Article Model:

require 'active_resource'

class Article  < ActiveResource::Base
  self.site = "http://localhost:3000"
end

Frontend Site Articles Controller:

class ArticlesController < ApplicationController
  def index
    @articles = Article.where(:is_published => true)
    @news = Article.where(:is_published => true, :news => true)
    @users = User.all
  end
end

Frontend site Article index.html.erb:

<div id='outer-wrapper'>
      <div class='margin-1200'>
         <div id='content-wrapper'>
            <!--Featured Post Home-->
            <div class='coverflow section' id='coverflow'>
                   <ul id="lightSlider">
                   <% @news.each do |news| %>
                   <% if news.is_published? %>
<li class="recent-box" style="overflow: hidden; float: left; width: 395px; height: 292px;"><div class="imageContainer"><a target="_top" href="<%= seofy_article_url(news) %>"><img alt="<%= news.title %>" title="<%= news.title %>" src="<%= api_domain_image(news) %>" class="label_thumb"></a></div>
<%= link_to news.title, seofy_article_url(news), :class => "label_title" %>
<div class="toe"><span class="post-date" href="http://socioism.blogspot.com/2015/01/the-year-2015.html"><i class="fa fa-calendar"></i> <%= article_date(news) %></span><span target="_top" href="http://socioism.blogspot.com/2015/01/the-year-2015.html#comment-form" class="recent-com"><i class="fa fa-comment"></i> 12 Comments</span></div></li>

<% else %>
No NEWS!
<% end %>

<% end %>

    </ul>
            </div>

<div style="clear:both;"></div>
<div class="index">

            <div id='main-wrapper'>
               <div class='main section' id='main'>
                  <div class='widget Blog' data-version='1' id='Blog1'>
                     <div class='blog-posts hfeed'>
                        <% @articles.each do |article| %>
                        <% if article.is_published? %>
                        <div class="date-outer">
                           <div class="date-posts">
                              <div class='post-outer'>
                                 <div class='wrapfullpost'>
                                    <div class='post hentry'>
                                       <a name='1001054977757960770'></a>
                                       <div class='post-header-line-1'></div>
                                       <div class='post-body entry-content'>
                                          <div class='post-summary' id='summary1001054977757960770'>
                                             <div dir="ltr" style="text-align: left;" trbidi="on">
                                                <div dir="ltr" style="text-align: left;" trbidi="on">
                                                   <div class="separator" style="clear: both; text-align: left;">
                                                      <img border="0" src="<%= api_domain_image(article) %>" />
                                                   </div>
                                                   <br />
                                                </div>

                                                <div>

                                                </div>

                                             </div>
                                          </div>

                                          <h2 class='post-title entry-title pagetitle'>
                                             <a href='<%= seofy_article_url(article) %>'><%= article.title.first(40) %>...</a>
                                          </h2>
                                          <div class='post-details'>
                                             <span class='post-date'><i class='fa fa-calendar'></i>
                                             <%= article_date(article) %></span>
                                             <span class='post-label'><i class='fa fa-tags'></i>
                                             <%= article.tags %></span>
                                          </div>
                                          <div style='clear: both;'></div>
                                       </div>
                                    </div>
                                 </div>
                              </div>

                           </div>
                        </div>
                        <% end %>
                        <% end %>
                     </div>

                  </div>
               </div>
            </div>
            <!-- end main wrapper -->

         </div>
         <!-- end content-wrapper -->
      </div>
   </div>
   <!-- end outer-wrapper -->
</div>
</div>

For some reason the definitions which I have set don't seem to have any affect because no matter what the @news is the same at @articles even though I have set what I want specifically using where.

RailsNewb
  • 3
  • 4

1 Answers1

1

What I understand is that you want to return a multipart JSON containing more than 1 type of resources, articles, news and users in your case. And if I understand it right, here's a piece of code which might help you.

Let's say you have a controller called manage_content.rb, write a function inside it.

def return_content
   @articles = Article.where(:is_published => true).order('created_at DESC').page(params[:page]).per(6)
    @news = Article.where(:news => true)
    @users = User.all
    # This is will create a single object with embedded arrays of your resource objects inside.
    @content = {
       articles: @articles,
       news: @news,
       users: @users
    }

    render json: { :data => @content, :status => 200 }
end

And in your config/routes.rb, add the corresponding route

get 'render_content' => "manage_content#return_content"

Test it by firing localhost:3000/render_content from your broswer. This should render you a JSON like,

{ 
   data: 
   {
      articles: [
          {.....},
          {.....}
      ],
      news: [
          {.....},
          {.....}
      ],
      users: [
          {.....},
          {.....}
      ]
    },
    status: 200
}

Remember that articles, users and news are JSON arrays. Mind the arrays and objects while parsing the json response at your front-end.

Regards.

Soumojit Ghosh
  • 921
  • 7
  • 16
  • Thanks, it works! Now I'm getting a expected an attributes Hash, got ["data" error on my frontend site, any idea how I can fix this ? – RailsNewb Jun 24 '16 at 14:00
  • Can you do a console.log from your front-end and see the JSON output? My guess here is that HTTP already has an attribute called data and we are embedding data again in our controller. You are probably doing a .data in your front-end. I think doing a .data.data will get you the desired object. Upon that you can do a .articles, .news and .users to get the individual arrays. Kindly accept the answer if it worked. – Soumojit Ghosh Jun 27 '16 at 09:51