Rails XML builder templates / group data
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!
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).
精彩评论