【问题标题】:render multiple queries as json in rails controller在 Rails 控制器中将多个查询呈现为 json
【发布时间】:2015-02-03 19:49:10
【问题描述】:

我有两个 Rails 控制器操作:

  def show
    @project = Project.find(params[:id])
    render json: @project,
      :only => [:id, :compilation_id],
      :methods => :track_name,
      :include => {
        :user => { :only => [:id, :email] }
      }
  end

  def list_users
    render json: User.select(:id, :email)
  end

我想在一个响应中同时呈现它们。这样做的最佳方法是什么?我尝试使用to_json 描述的here 方法,但我读到该方法已被弃用,我还注意到它转义了似乎不必要的内容。任何帮助表示赞赏。

【问题讨论】:

  • 答案解决了你的问题吗?
  • @dgilperez- 不,您的回答没有解决在一个响应中渲染两个模型的问题。不过,这些信息很有用,我给了你一个赞成票。
  • 试试jbuilder,我一直用它来渲染复杂的json响应。

标签: ruby-on-rails json ruby-on-rails-4 rails-activerecord


【解决方案1】:

对于需要足够复杂的 json 结构以使 to_json 看起来可读的情况,我建议使用 active_model_serializers gem。

然后你可以像这样定义两个序列化器类:

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :compilation_id

  has_many :users
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email
end

然后在你的控制器中:

class ProjectsController < ApplicationController
  def show
    @project = Project.find(params[:id])
    render json: @project, serializer: ProjectSerializer, status: 200
  end
end

作为奖励曲目,你甚至可以cache the response

【讨论】:

    【解决方案2】:

    当然,解决方案非常简单:

    project = Project.select(:id, :compilation_id, :user_id, :genre_id, :ordering).find(params[:id])
    render json: { :project => project,
                   :users => User.select(:id, :email),
                   :genres => Genre.select(:id, :name),
                   :track_name => project.track_name
                 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多