Jbuilder没有在集合中包装单个对象

时间:2015-08-18 19:29:12

标签: ruby-on-rails json jbuilder

我的rails应用程序中有一个索引视图,允许通过搜索参数进行过滤。当一组op文章被返回时,它会被app.controller('FormController', ['$scope', 'tocFactory', function ($scope, tocFactory) { $scope.books; getBooks(); function getBooks() { tocFactory.getBooks(). success(function(data, status, headers, config) { $scope.books = data; console.log($scope.books); }). error(function(data, status, headers, config) { // log error }) } console.log($scope.books); }]); articles这样的集合所淹没。但是,如果只找到一个对象,则{"articles":[{"article":{"id":341,"updated":"2015-08-18T13:05:08.427Z","title":"级别丢失,articles。如何修复它以使单个对象的行为类似于多个?

_articles.list.json.jbuilder

{"article":{"id":398,"updated":"2015-08-07T11:37:26.200Z","title":

index.json.jbuilder

require 'uri'
require 'publish_on'
json.cache! ['v1', articles] do
  json.articles articles do |article|
    json.cache! ['v1', article] do
      json.article do
        json.id article.id
        json.updated as_ns_date(article.updated_at)
        json.title article.label
        json.numberOfViews article.view_mappings.count
        json.numberOfFavorites article.favorite_mappings.count
        json.imageURLs article.images if article.images.any?
        json.youtubeURL article.youtube unless article.youtube.blank?
        json.tags article.categories.map(&:label)
        json.isFeatured article.featured
        json.isPublished article.is_published
        json.published as_ns_date(article.publish_on)
      end
    end
  end
end

articles_controller.rb

json.partial! 'articles/articles_list', articles: @articles

search_articles_command.rb

  def index
    @articles = SearchArticlesCommand.new(params).execute
    render :index
  end

article.rb

class SearchArticlesCommand
  def initialize(params = {})
    @since = params[:since_date]
    @keys = params[:search_query]
    @category = params[:category]
  end

  def execute
    Article.unscoped do
      query = if @since.present?
        Article.article.since_date(@since)
      else
        Article.published_article
      end
      query = query.search_by_keywords(@keys) if @keys.present?
      query = query.search_by_category(@category) if @category.present?
      query.select(:id, :updated_at, :label, :is_published, :featured, :slug, :created_at).order(created_at: :desc)
    end
  end
end

1 个答案:

答案 0 :(得分:1)

这是我怀疑的。如果您想要相同的行为,查询应该在找到一篇或多篇文章时返回相同类型的对象。问题是,要么根据您的参数返回ActiveRecordRelationArticle对象。

@articles = Article.all     # => ActiveRecordRelation, an array per se
@articles = Article.find(1) # => Article object

jbuilder构造JSON时,它检查它是否是一个对象数组,然后用{ keyword => array }包装json。如果它是单个对象,则默认为单个对象{article: {}}

解决方案很简单,您可以调整SearchArticlesCommand以始终返回ActiveRecordRelation,即使它只找到一个对象。

相关问题