ted
ted

Reputation: 5329

Rails: map nested attribute to model's object

# models
class A < ActiveRecord::Base
    has_many :b

class B < ActiveRecord::Base
    belongs_to :a

# controllers
class aController < ApplicationController
    def a_with_b
        @a_with_b = A.find(1, :include => [:b])
        puts @a_with_b # => #<A id:1> // `b` not mapped to `@a_with_b`
        puts @a_with_b.b # => [#<B id:1>, #<B id:2>] // still there's `b`
    end
end

Question:
How can b be mapped to @a_with_b?
Expected:

puts @a_with_b # => #<A id:1 b:[#<B id:1>, #<B id:2>] >

The actual reason for all written above is to be able to get serialized object with the appropriate structure: e.g.

{something: true, nothing: false, a: @a_with_b}.to_xml # =>

<xml>
  <something>true</something>
  <nothing>false</nothing>
  <a>
    <id>1</id>
    <bs>
      <b> <id>1</id> </b>
      <b> <id>2</id> </b>
    </bs>
  </a>
<xml>

Rails v.2.3

Upvotes: 0

Views: 1524

Answers (2)

Yanhao
Yanhao

Reputation: 5294

If you want to serialize the data in JSON, you can do it like this:

@a_with_b = A.find(1, :include => [:b])
puts @a_with_b.to_json(:include => [:b]) # return a JSON encoded string
puts @a_with_b.as_json(:include => [:b]) # return a Hash

Upvotes: 1

heartpunk
heartpunk

Reputation: 2275

I just spent some time poking around in the implementation of this, and it looks like what happens is the data is pulled from the database, and put into the activerecord object cache, such that if you reference them, it won't require a database query. The objects do not end up nested in the way it seems you want, but I can't think of a reason this should be a problem.

In other words, unless you see that the SQL query being generated doesn't meet your expectations, this is probably the desired behavior.

Upvotes: 0

Related Questions