2

我正在尝试将以下方法添加到 Spree 模型中。#to_csv_test

这就是我尝试这样做的方式:

Spree::Order.class_eval do
  def self.to_csv_test(options = {})
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |order|
        csv << order.attributes.values_at(*column_names)
      end
    end
  end
end

但是,如果我在控制台中尝试这个,我会得到以下信息:

sop = Spree::Order.order(:created_at)
  Spree::Order Load (0.2ms)  SELECT "spree_orders".* FROM "spree_orders" ORDER BY created_at
 => [#<Spree::Order id: 1, number: "R770265765", item_total: #<BigDecimal:7fd18a514ee8,'0.15E2',9(36)>, total: #<BigDecimal:7fd18a514e20,'0.2E2',9(36)>, state: "confirm", adjustment_total: #<BigDecimal:7fd18a514ba0,'0.5E1',9(36)>, user_id: 1, completed_at: nil, bill_address_id: 1, ship_address_id: 2, payment_total: #<BigDecimal:7fd18a51c760,'0.0',9(36)>, shipping_method_id: nil, shipment_state: "pending", payment_state: "balance_due", email: "spree@example.com", special_instructions: nil, created_at: "2013-07-01 22:25:19", updated_at: "2013-07-01 22:33:13", currency: "USD", last_ip_address: "127.0.0.1">, #<Spree::Order id: 2, number: "R261116333", item_total: #<BigDecimal:7fd18a51a168,'0.0',9(36)>, total: #<BigDecimal:7fd18a519cb8,'0.0',9(36)>, state: "cart", adjustment_total: #<BigDecimal:7fd18a519498,'0.0',9(36)>, user_id: nil, completed_at: nil, bill_address_id: nil, ship_address_id: nil, payment_total: #<BigDecimal:7fd18a518bd8,'0.0',9(36)>, shipping_method_id: nil, shipment_state: "pending", payment_state: "balance_due", email: nil, special_instructions: nil, created_at: "2013-07-02 03:16:45", updated_at: "2013-07-02 03:16:45", currency: "USD", last_ip_address: nil>]
1.9.3p429 :041 > sop.to_csv_test
NoMethodError: undefined method `to_csv_test' for #<ActiveRecord::Relation:0x007fd18a50d0f8>
4

1 回答 1

2

我实际上对您在这里尝试做的事情感到困惑。为什么要对这个实例采取行动以将所有订单输入 CSV?也许这就是你想要的?

Spree::Order.instance_eval do
  def to_csv_test(options = {})
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |order|
        csv << order.attributes.values_at(*column_names)
      end
    end
  end
end

此外,这里是 instance_eval 和 class_eval http://www.jimmycuadra.com/posts/metaprogramming-ruby-class-eval-and-instance-eval的更好解释

于 2013-07-02T04:54:39.007 回答