'to_json'中的':methods'选项可以用':only'选项替换吗?

时间:2017-12-08 02:49:56

标签: ruby-on-rails json

Sub Main() If Directory.Exists(MyPath) Then RenameAll(MyPath) Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...") Console.ReadLine() Else Console.WriteLine(vbCrLf + "Path is invalid") Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...") Console.ReadLine() End If End Sub 选项包含选项to_json:only。前者旨在接受属性和后一种方法。

我有一个具有属性:methods的模型,该模型被覆盖:

foo

无论我在class SomeModel < ActiveRecord::Base ... def foo # Overrides the original attribute `foo` "the overwritten foo value" end end 下编写哪个选项,似乎都会调用覆盖的foo方法。

foo

这似乎表明我使用SomeModel.first.to_json(only: [:foo]) # => "{..., \"foo\":\"the overwritten foo value\", ...}" SomeModel.first.to_json(methods: [:foo]) # => "{..., \"foo\":\"the overwritten foo value\", ...}" 还是:only并不重要。

是这样的吗?我觉得我的想法有问题。

源代码导致这些:

文件activemodel / lib / active_model / serialization.rb,第124行

:methods

文件activeresource / lib / active_resource / base.rb,第1394行

def serializable_hash(options = nil)
  options ||= {}

  attribute_names = attributes.keys
  if only = options[:only]
    attribute_names &= Array(only).map(&:to_s)
  elsif except = options[:except]
    attribute_names -= Array(except).map(&:to_s)
  end

  hash = {}
  attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }

  Array(options[:methods]).each { |m| hash[m.to_s] = send(m) }

  serializable_add_includes(options) do |association, records, opts|
    hash[association.to_s] = if records.respond_to?(:to_ary)
      records.to_ary.map { |a| a.serializable_hash(opts) }
    else
      records.serializable_hash(opts)
    end
  end

  hash
end

似乎def read_attribute_for_serialization(n) attributes[n] end 选项调用:onlyattributes[n]选项调用:methods。有什么区别?

0 个答案:

没有答案