gpt4 book ai didi

ruby-on-rails - as_json 不支持参数化方法

转载 作者:行者123 更新时间:2023-12-04 05:43:56 26 4
gpt4 key购买 nike

在 'as_json'/'to_json' 中传递方法来创建对象的 json 响应时,我们不能在方法中传递参数。 'as_json/to_json' 不支持它背后的原因是什么

例如,

@posts.to_json(
:only => [:title, :body, :created_at, :tags, :category],
:methods => [:likes_count, :comments_count])
}

这里我们不能传递带参数的方法。

最佳答案

这不是开箱即用的,但我们可以构建它。
对于 Rails 3.2。将此添加到 config/initializers/full_json.rb .

module ActiveModel
module Serializers
module JSON
def as_full_json(options = nil)
root = include_root_in_json
root = options[:root] if options.try(:key?, :root)
if root
root = self.class.model_name.element if root == true
{ root => fully_serializable_hash(options) }
else
fully_serializable_hash(options)
end
end
end
end
end

module ActiveModel
module Serialization
def fully_serializable_hash(options = nil)
options ||= {}

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

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

# These two lines do the magic. I check if it's Array, and in case it is, it should accept the arguments.
method_names = Array.wrap(options[:methods]).select { |n| respond_to?(Array.wrap(n).first) }
method_names.each { |n| n.is_a?(Array) ? (hash[n.first] = send(*n)) : (hash[n] = send(n)) }

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

hash
end
end
end

尝试:
# Here method_with_arg is the method which accepts argument. 'arg' is the argument
@posts.as_full_json(
:only => [:title, :body, :created_at, :tags, :category],
:methods => [:likes_count, :comments_count, [:method_with_arg, 'arg']])
}.to_json

我确信可以清理和减少此代码。可能通过使用别名链或其他东西。你可以进一步做。让我知道这是否适合您。

干杯

关于ruby-on-rails - as_json 不支持参数化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39247358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com