使用选项配置块进行序列化

发布于 2024-11-15 03:00:17 字数 899 浏览 3 评论 0原文

我正在使用 serialize_with_options ( http://www.viget.com/extend/ simple-apis-using-serializewithoptions/ )在 Rails 项目中,并按照链接页面上的示例使用命名块进行渲染:

class Speaker < ActiveRecord::Base
  # ...

  serialize_with_options do
    methods   :average_rating, :avatar_url
    except    :email, :claim_code
    includes  :talks
  end

  serialize_with_options :with_email do
    methods   :average_rating, :avatar_url
    except    :claim_code
    includes  :talks
  end

end

然后我可以使用以下命令调用第二个块配置 : @speaker.to_xml(:with_email)。这很好用,但是,我想弄清楚当我有一个对象数组时如何调用这个块。例如,以下内容不起作用:

@speakers = Speaker.all
@speakers.to_xml(:with_email)

它返回“TypeError:无法复制符号”错误。这对我来说很有意义,因为数组尚未配置为使用serialize_with_options。在运行 .to_xml 并渲染所有扬声器 :with_email 时,如何将此标签传递给各个扬声器对象?

I'm using serialize_with_options ( http://www.viget.com/extend/simple-apis-using-serializewithoptions/ ) in a rails project and have been using named blocks for rendering as per the example on the linked page:

class Speaker < ActiveRecord::Base
  # ...

  serialize_with_options do
    methods   :average_rating, :avatar_url
    except    :email, :claim_code
    includes  :talks
  end

  serialize_with_options :with_email do
    methods   :average_rating, :avatar_url
    except    :claim_code
    includes  :talks
  end

end

Then I can call the second block configuration with @speaker.to_xml(:with_email). This works well, however, I'd like to figure out how to call this block when I have an array of objects. For example, the following does not work:

@speakers = Speaker.all
@speakers.to_xml(:with_email)

Which returns a "TypeError: can't dup Symbol" error. This makes sense to me since Array hasn't been configured to use serialize_with_options. How can I get this tag to be passed on to the individual speaker objects when running .to_xml and render all speakers :with_email?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够钟 2024-11-22 03:00:17

在上面的示例中,@speakers 是一个 Array 对象。您需要在那里实现/覆盖 to_xml 。那我应该工作:

class Array
    def to_xml (with_email)
        self.each do |element|
            element.to_xml(with_email)
        end
    end
end

In your above example, @speakers is a Array object. You need to implement / override the to_xml there . Then i should work:

class Array
    def to_xml (with_email)
        self.each do |element|
            element.to_xml(with_email)
        end
    end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文