【问题标题】:ActiveRecord serialize two different models in at onceActiveRecord 一次序列化两个不同的模型
【发布时间】:2015-08-23 18:27:06
【问题描述】:

我的 Rails 应用程序中有一个控制器操作 (favorites),它返回一个带有两个键(companiesjobs)的 JSON 对象。每个键代表CompanyJobDescription 对象的集合。我想知道是否有一种干净的方法可以同时序列化@companies@jobs。这是我的代码:

def favorites
    @companies = current_user.companies
    @jobs = current_user.job_descriptions

    respond_to do |format|
        format.html
        format.json { render json: {companies: @companies, jobs: @jobs}, root: false }
    end
end

我总是可以将我的代码重构为两个单独的 JSON 调用(一个用于工作,一个用于公司),但我更愿意坚持对 favorites 的单个调用。

【问题讨论】:

    标签: ruby-on-rails json activerecord


    【解决方案1】:

    您可以在这里使用 Rails Presenters!

    因此,您可以有两个演示者:CompaniesPresenterJobsPresenter,它们将分别负责构建 @companiesjobs 对象。

    因此,在您的控制器中,您将拥有如下内容:

    @companies = CompaniesPresenter.new(current_user).companies
    @jobs = JobsPresenter.new(current_user).job_descriptions
    

    例如,您的CompaniesPresenter 如下所示:

    class CompaniesPresenter
      attr_reader :current_user
    
      def initialize(current_user)
        @current_user = current_user
      end
    
      def companies
        # build the companies JSON here 
      end
    end
    

    Here 是一个可能有用的 Rails Presenter Pattern 教程。

    而且,here 是一个有用的视频。希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      这个例子有效,你只是想改变 json 格式吗?如果是这样……

      在公司或职位模型中,你可以添加一个 as_json 方法,并根据需要格式化输出。

      def as_json(options = {})
        { :name => name }
      end
      

      【讨论】:

        猜你喜欢
        • 2011-04-30
        • 2014-06-06
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-21
        相关资源
        最近更新 更多