ruby on rails - Query nested model with multiple plucks -


i wondering if following possible: have model nested associative models. want able render json: on current_user.reports.minned , have eager_load plucked values each model. how can accomplish this?

here use 2 models example. in reality, solution needs work n+1 nested models.

does not work:

class report   has_many :templates    def minned     self.pluck(:id, :title)     self.templates = templates.minned   end end  class template   belongs_to :report    def minned     self.pluck(:id, :name, :sections, :columns)   end end  ....  # reports.minned.limit(limit).offset(offset) # should return like: [{   'id': 0,   'title': 'rep',   'templates': [{     'id': 0,     'name': 'temp'     'sections': [],     'columns': []   }] }, {   'id': 1,   'title': 'rep 1',   'templates': [{     'id': 0,     'name': 'temp',     'sections': [],     'columns': []   },   {     'id': 1,     'name': 'temp 1',     'sections': [],     'columns': []   }] }] 

thanks help.

edit:

i add found way overriding as_json each model, applies plucking requests. need have control on requests give pieces of information.

# in report model def as_json(options={})   super(:id, :title).merge(templates: templates) end  # in template model def as_json(options={})   super(:id, :name, :sections, :columns) end 

thanks eirikir, need do:

report model

def self.minned   includes(:templates).as_json(only: [:id, :title], include: {templates: {only: [:id, :name, :sections, :columns]}}) end 

then when using pagination order, limit or that, drop @ end:

  paginate pre_paginated_reports.count, max_per_page |limit, offset|     render json: pre_paginated_reports.order(id: :desc).limit(limit).offset(offset).minned   end 

now i'm not overriding as_json , have complete control on data back.

if understand correctly, should able achieve specifying output in options given as_json:

current_user.reports.includes(:templates).as_json(only: [:id, :title], include: {templates: {only: [:id, :name, :sections, :columns]}}) 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -