2016-06-24 7 views
-1

컨트롤러에 여러 개의 Json 렌더링을 렌더링하고 싶습니다. 나는 모델 serializer gem을 사용하여 레일 Json API를 가지고있다. 지금은 하나의 객체 만 렌더링 할 수 있습니다. 내가하고 싶은 것은 또한 @news와 @users를 렌더링하는 것이지만 지금은 @articles 만 렌더링하고 있습니다.Rails 렌더링 다중 컨트롤러에서 Json API 사용

백엔드 기사 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에서 동일하기 때문에 비록 내가 어디에서 구체적으로 원하는 것을 설정 했음에도 불구하고.

답변

1

내가 알고있는 것은 귀하의 경우에 2 가지 유형의 리소스, 기사, 뉴스 및 사용자가 포함 된 멀티 파트 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 

그리고 당신의 설정/routes.rb에서

은, 당신이 broswer에서 localhost:3000/render_content을 발사하여 해당 경로

get 'render_content' => "manage_content#return_content" 

테스트에 추가합니다. 이렇게하면 JSON을 좋아할 것입니다.

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

아티클, 사용자 및 뉴스는 JSON 배열입니다. 프론트 엔드에서 json 응답을 파싱하는 동안 배열과 객체를주의하십시오.

감사합니다.

+0

감사합니다. 작동합니다! 이제 예상되는 속성 해시를 얻고 있습니다. [프론트 엔드 사이트에서 "데이터"오류가 발생하며이를 해결할 수있는 방법이 있습니까? – RailsNewb

+0

프론트 엔드에서 console.log를 수행하고 JSON 출력을 볼 수 있습니까? 내 생각 엔 HTTP에는 이미 data라는 속성이 있으며 우리 컨트롤러에 데이터가 다시 포함되어 있다고 생각합니다. 프론트 엔드에서 .data를하고있을 것입니다. .data.data를 수행하면 원하는 개체를 얻을 수 있다고 생각합니다. 이 때, .articles, .news 및 .users를 사용하여 개별 배열을 얻을 수 있습니다. 답변이 제대로 작동하면 친절하게 답변 해주십시오. –