to_xml 不适用于通过 Rails ActiveRecord habtm 参考返回的对象

发布于 2024-11-26 04:28:26 字数 4690 浏览 1 评论 0原文

我有两个 Rails 活动记录类,即 School 和 Instructor,通过 has_and_belongs_to_many 关系链接。

我需要在 coachs_controller 中查询特定学校的讲师并返回 xml 格式的响应。因此,在索引方法中我有这个代码片段:

school = School.find(params[:school_id])
@instructors = school.instructors

和后来的:

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @instructors }
  format.json { render :json => @instructors }
end

但它不起作用。看看这个有趣但令人困惑的序列:

ruby-1.9.2-p180 :023 >   Instructor.all.first
=> #<Instructor id: 1, name: "Mrs. Smith", instructor_type_id: 1, created_at: "2011-07-24 18:19:40", updated_at: "2011-07-24 18:19:40"> 

ruby-1.9.2-p180 :026 > Instructor.all.first.class
 => Instructor(id: integer, name: string, instructor_type_id: integer, created_at: datetime, updated_at: datetime) 

ruby-1.9.2-p180 :024 > School.first.instructors.first
 => #<Instructor id: 1, name: "Mrs. Smith", instructor_type_id: 1, created_at: "2011-07-24 18:19:40", updated_at: "2011-07-24 18:19:40"> 

ruby-1.9.2-p180 :025 > School.first.instructors.first.class
 => Instructor(id: integer, name: string, instructor_type_id: integer, created_at: datetime, updated_at: datetime) 

ruby-1.9.2-p180 :021 > Instructor.all.first.to_xml
 => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<instructor>\n  <created-at type=\"datetime\">2011-07-24T18:19:40Z</created-at>\n  <id type=\"integer\">1</id>\n  <instructor-type-id type=\"integer\">1</instructor-type-id>\n  <name>Mrs. Smith</name>\n  <updated-at type=\"datetime\">2011-07-24T18:19:40Z</updated-at>\n</instructor>\n" 

现在是重点:

ruby-1.9.2-p180 :019 > School.first.instructors.first.to_xml

NoMethodError: undefined method `type' for nil:NilClass
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activerecord-3.0.9/lib/active_record/serializers/xml_serializer.rb:230:in `compute_type'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:22:in `initialize'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:75:in `new'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:75:in `block in serializable_attributes'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:74:in `each'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:74:in `map'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:74:in `serializable_attributes'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:116:in `add_attributes_and_methods'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:103:in `block in serialize'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:31:in `tag!'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:102:in `serialize'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activerecord-3.0.9/lib/active_record/serializers/xml_serializer.rb:175:in `to_xml'
    from (irb):19
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'ruby-1.9.2-p180 :020 > Instructor.all.first.to_xml

这里发生了什么?

编辑:嗯,从 xml 切换到 json 解决了问题,(to_json 在这里没有表现出与 to_xml 相同的奇怪性),尽管我仍然想知道上述行为的解释。

另外,由于我对 Rails 比较陌生,有没有更好的方法来做我想做的事情?

I have two rails active record classes, School and Instructor linked by a has_and_belongs_to_many relationship.

I need to query my instructors_controller for instructors for a particular school and return an xml format response. Therefore, in the index method I have this code fragment:

school = School.find(params[:school_id])
@instructors = school.instructors

and later:

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @instructors }
  format.json { render :json => @instructors }
end

But it doesn't work. Look at this intriguing but baffling sequence:

ruby-1.9.2-p180 :023 >   Instructor.all.first
=> #<Instructor id: 1, name: "Mrs. Smith", instructor_type_id: 1, created_at: "2011-07-24 18:19:40", updated_at: "2011-07-24 18:19:40"> 

ruby-1.9.2-p180 :026 > Instructor.all.first.class
 => Instructor(id: integer, name: string, instructor_type_id: integer, created_at: datetime, updated_at: datetime) 

ruby-1.9.2-p180 :024 > School.first.instructors.first
 => #<Instructor id: 1, name: "Mrs. Smith", instructor_type_id: 1, created_at: "2011-07-24 18:19:40", updated_at: "2011-07-24 18:19:40"> 

ruby-1.9.2-p180 :025 > School.first.instructors.first.class
 => Instructor(id: integer, name: string, instructor_type_id: integer, created_at: datetime, updated_at: datetime) 

ruby-1.9.2-p180 :021 > Instructor.all.first.to_xml
 => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<instructor>\n  <created-at type=\"datetime\">2011-07-24T18:19:40Z</created-at>\n  <id type=\"integer\">1</id>\n  <instructor-type-id type=\"integer\">1</instructor-type-id>\n  <name>Mrs. Smith</name>\n  <updated-at type=\"datetime\">2011-07-24T18:19:40Z</updated-at>\n</instructor>\n" 

Now for the punchline:

ruby-1.9.2-p180 :019 > School.first.instructors.first.to_xml

NoMethodError: undefined method `type' for nil:NilClass
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activerecord-3.0.9/lib/active_record/serializers/xml_serializer.rb:230:in `compute_type'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:22:in `initialize'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:75:in `new'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:75:in `block in serializable_attributes'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:74:in `each'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:74:in `map'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:74:in `serializable_attributes'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:116:in `add_attributes_and_methods'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:103:in `block in serialize'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/builder-2.1.2/lib/builder/xmlbase.rb:31:in `tag!'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activemodel-3.0.9/lib/active_model/serializers/xml.rb:102:in `serialize'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/activerecord-3.0.9/lib/active_record/serializers/xml_serializer.rb:175:in `to_xml'
    from (irb):19
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
    from /usr/local/rvm/gems/ruby-1.9.2-p180@blueprint/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'ruby-1.9.2-p180 :020 > Instructor.all.first.to_xml

What's going on here ?

Edit: Well, switching from xml to json solved the problem, (to_json does not exhibit the same strangeness as to_xml here), although I would still like to know the explanation for the above behavior.

Also, as I am relatively new to Rails, is there a better way to do what I want to do here ?

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

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

发布评论

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

评论(1

夜唯美灬不弃 2024-12-03 04:28:26

to_xml() 尝试为每个模型属性定义一个类型属性。例如,具有年龄 (INT) 属性的用户模型将具有:42。此类型信息未编码为 JSON,这就是 to_json() 适合您的原因。将此方法添加到您的 Instructor 模型中:

def to_xml(options = {})
  to_xml_opts = {:skip_types => true} # no type information, not such a great idea!
  to_xml_opts.merge!(options.slice(:builder, :skip_instruct))
  # a builder instance is provided when to_xml is called on a collection of instructors,
  # in which case you would not want to have <?xml ...?> added to each item
  to_xml_opts[:root] ||= "instructor"
  self.attributes.to_xml(to_xml_opts)
end

但是,这会使您的 XML 缺乏任何类型信息 - 如果有人拥有 JAVA REST 客户端,则不好。更好的策略是过滤 self.attributes.slice(*keys).to_xml(to_xml_opts) ,其中 keys 是您希望在 XML 中包含的模型属性数组。

to_xml() tries to define a type attribute for each model attribute. For example, a User model with an age (INT) attribute will have: <age type="integer">42</age>. This type information is not encoded in JSON, which is why to_json() works for you. Add this method to your Instructor model:

def to_xml(options = {})
  to_xml_opts = {:skip_types => true} # no type information, not such a great idea!
  to_xml_opts.merge!(options.slice(:builder, :skip_instruct))
  # a builder instance is provided when to_xml is called on a collection of instructors,
  # in which case you would not want to have <?xml ...?> added to each item
  to_xml_opts[:root] ||= "instructor"
  self.attributes.to_xml(to_xml_opts)
end

This would however make your XML devoid of any type information - not good if someone has a JAVA REST client. A better strategy would be to filter self.attributes.slice(*keys).to_xml(to_xml_opts) where keys is an array of model attributes you want in the XML.

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