加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用选项配置块进行序列化

发布时间:2020-12-16 19:07:45 所属栏目:百科 来源:网络整理
导读:我在rails项目中使用serialize_with_options( http://www.viget.com/extend/simple-apis-using-serializewithoptions/),并且已根据链接页面上的示例使用命名块进行渲染: class Speaker ActiveRecord::Base # ... serialize_with_options do methods :averag
我在rails项目中使用serialize_with_options( http://www.viget.com/extend/simple-apis-using-serializewithoptions/),并且已根据链接页面上的示例使用命名块进行渲染:
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:can not dup Symbol”错误.这对我来说很有意义,因为Array尚未配置为使用serialize_with_options.在运行.to_xml并渲染所有发言者时,如何将此标记传递给各个发言人对象:with_email?

解决方法

在上面的示例中,@speakers是一个Array对象.你需要在那里实现/覆盖to_xml.那我应该工作:
class Array
    def to_xml (with_email)
        self.each do |element|
            element.to_xml(with_email)
        end
    end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读