2013-07-02 48 views
2

我想將以下方法添加到Spree模型。 #to_csv_testNoMethodError:未定義的方法`to_csv_test'爲ActiveRecord ::關係

這是我正在努力做到這一點:

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: "[email protected]", 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> 

回答

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

相關問題