ruby jsonapi_suite内存关联的侧载

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby jsonapi_suite内存关联的侧载相关的知识,希望对你有一定的参考价值。

# In-memory associations as jsonapi_suite sideloads
# Using the trick of memoization, assuming the parent known about the children
# 
# @example 
#   The parent could have a `field type_string, type: String`
#   and a method #type that calls and memoizes `self.type_string.camelize.constantize`
#

class Parent
  def association_in_memory
    @association_in_memory ||= code_to_get_all_association
  end

  def my_child?(child)
    # ...
  end
end

class Child
  # nothing particular
end

allow_sideload :association_in_memory, resource: InMemoryResource do
  # Read the association in memory, 
  # we flatten everything in the same array
  scope do |parents|
    parents.all.flat_map(&:association_in_memory) # before they get filtered or whatever
  end

  # Now our flattened array was just filtered, we need to "reassign" what was previously assigned to the right guy
  assign do |parents, children_in_memory_after_getting_filtered_or_whatever|
    tldr = children_in_memory_after_getting_filtered_or_whatever
    parents.each do |parent|
      children_belonging_to_parent = children_in_memory_after_getting_filtered_or_whatever.select do |child|
        parent.my_child?(child)
      end
      parent.instance_variable_set('@association_in_memory', children_belonging_to_parent)
    end
  end
end

以上是关于ruby jsonapi_suite内存关联的侧载的主要内容,如果未能解决你的问题,请参考以下文章

Ember:访问模板中的侧载模型关系数据

为啥我的侧载 Excel Javascript 加载项在外部浏览器中打开,而不是在任务窗格中打开?

没有 CoreData 的 RestKit 侧载 JSON 关联

text 适用于jsonapi_suite的Mongoid适配器

学说:指拥有不存在的侧场(再次)

为不在应用商店中的 iOS 应用使用推送通知