Rails在控制器中渲染多个使用Json API

时间:2016-06-24 12:19:44

标签: ruby-on-rails ruby json api respond-to

我希望能够在我的控制器中渲染多个Json渲染器。我有一个使用Model serializers gem的rails Json API。目前我只能渲染一个物体。我想做的是渲染@ news和@users但是现在我只渲染@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

前端网站文章模型:

require 'active_resource'

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

前端网站文章控制器:

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

前端网站文章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>

由于某种原因,我设定的定义似乎没有任何影响,因为无论@ news上的@news是什么,即使我已经设置了我想要的具体使用位置。

1 个答案:

答案 0 :(得分:1)

据我所知,您希望在您的案例中返回包含多种资源,文章,新闻和用户的多部分JSON。如果我理解正确,这里有一段可能对你有帮助的代码。

假设您有一个名为manage_content.rb的控制器,在其中编写一个函数。

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

在config / routes.rb中,添加相应的路由

get 'render_content' => "manage_content#return_content"

通过从你的broswer中解雇localhost:3000/render_content来测试它。这应该会给你一个JSON,

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

请记住,文章,用户和新闻都是JSON数组。在解析前端的json响应时注意数组和对象。

问候。