views:

225

answers:

1

My SQL result @products=Product.find_by_sql() gives me this (

ID  title,     user_name
1   Product1   Xpeper
1   Product1   John
2   Product2   Xpeper

How can I build XML in my xml.builder view file so the source bould be like this

<products>
    <product>
      <id>1</id>
      <title>Product1</title>
      <users>
        <user>Xpeper</user>
        <user>John</user>
      </users>
    </product>
    <product>
      <id>2</id>
      <title>Product2</title>
      <users>
        <user>Xpeper</user>
      </users>
    </product>
</products>

I would like to group items by products. Thx!

A: 

One way you could do it is to separate the User and the Product, having a many to many relationship (has_and_belongs_to_many) between them. I'm imagining that you already have a separate Users model.

With the has_and_belongs_to_many relationship you will be able to access the users a product has in @product.users (an array).

adamse
An example? The two models are linked with inner join.
xpepermint
I don't know how you have solved it, or if you have access to the database tables. But this is how i would do it. I would have 2 models, one called User and one Product then there would be a many to many relationship between them (many to many is called has_many_and_belongs_to_may in rails) is you specify has_many_and_belongs_to_may in both models you can access the user which has the product at procuct.users and the products an user has at user.products.
adamse