【问题标题】:Rails Render Multiple in controller Using Json APIRails 使用 Json API 在控制器中渲染多个
【发布时间】:2016-06-24 12:19:43
【问题描述】:

我希望能够在我的控制器中渲染多个 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

后端文章序列化器:

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 在@articles 上是什么,即使我已经设置了我想要的具体使用位置。

【问题讨论】:

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


    【解决方案1】:

    我的理解是,在您的案例中,您希望返回一个包含超过 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"
    

    通过从您的浏览器中触发 localhost:3000/render_content 来测试它。这应该会为您呈现类似 JSON 的内容,

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

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

    问候。

    【讨论】:

    • 谢谢,它有效!现在我得到了一个预期的属性哈希,在我的前端站点上出现 ["data" 错误,知道如何解决这个问题吗?
    • 你能从你的前端做一个console.log并查看JSON输出吗?我的猜测是 HTTP 已经有一个名为 data 的属性,我们再次将数据嵌入到我们的控制器中。您可能正在前端做一个 .data 。我认为做一个 .data.data 会给你想要的对象。在那之后,您可以使用 .articles、.news 和 .users 来获取各个数组。如果有效,请接受答案。
    猜你喜欢
    • 2013-01-27
    • 2017-04-20
    • 2019-02-06
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多