您好,我正在尝试对产品及其属性进行排序,但问题是属性的标题不是基于产品的名称和描述。所以例如我有:
Product id | attribute 1 name | attribute 1 desc | attribute 2 name | attribute 2 desc
1001 | screen size | 15" | DCR | 10,000:1
1002 | DCR | 200,000:1 | Widescreen | yes
这一行一直持续到产品有多少属性为止。
我需要的是会吐出来的东西:
Product id, attribute 1 name, attribute 1 desc
Product id, attribute 2 name, attribute 2 desc
所以它看起来像这样:
1001, screen size, 15"
1001, DCR, 10,000:1
1002, DCR, 200,000:1
1002, widescreen, yes
有谁知道对这些信息进行排序的最佳方式是什么?
我一直在尝试使用一些 excel vba 脚本,但我想知道是否有一种方法可以用 ruby 来实现,因为这就是我现在正在学习的,这将是一个很好的现实世界的例子来深入研究变成 ruby 。
最佳答案
您可以通过将属性分离到它们自己的模型中来大大简化此过程。
应用/模型/product_attribute.rb
class ProductAttribute < ActiveRecord::Base
attr_accessible :name, :desc, :product_id
belongs_to :product
#...
end
应用/模型/product.rb
class Product < ActiveRecord::Base
# ...
has_many :product_attributes
# ...
def self.sorted_attributes
Product.all.collect{|prod| prod.sorted_attributes}
end
def sorted_attributes
product_attributes.all(order: "name ASC").collect{|attr| [self.id, attr.name, attr]}
end
end
然后您就可以通过调用 Product.sorted_attributes 并编写 View 代码来显示生成的二维数组来获取所需的信息。
关于ruby-on-rails - 从数据行中堆叠带有 id 的列对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13650804/