开发者

Rails XML builder templates / group data

开发者 https://www.devze.com 2022-12-15 07:23 出处:网络
My SQL result @products=Product.find_by_sql() gives me this ( IDtitle,user_name 1Product1Xpeper 1Product1John

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消