[英]Print array to CSV in Ruby on Rails?
在模型中,我有以下方法受到RailsCasts#362的啟發
該模型是Post,Post中的列稱為Author。 作者是一個字符串數組。 我想將Author數組中的每個條目循環到CSV文件自己的一行中,而不是僅將數組打印到一行中。 我正在Post.rb(模型類文件)中嘗試這樣做,但是我收到錯誤randomsched' for #<Class:0xccd0490>"
未定義局部變量或方法randomsched' for #<Class:0xccd0490>"
def self.to_csv(options = {})
CSV.generate(options) do |csv|
author.each do |x|
csv << x
end
end
end
回溯
Started GET "/posts.csv" for 127.0.0.1 at 2015-03-15 07:19:36 -0400
Processing by PostsController#index as CSV
Completed 500 Internal Server Error in 9ms
NameError (undefined local variable or method `author' for #<Class:0xccd0490>):
app/models/post.rb:26:in `block in to_csv'
app/models/post.rb:25:in `to_csv'
app/controllers/posts_controller.rb:10:in `block (2 levels) in index'
app/controllers/posts_controller.rb:8:in `index'
假設每個帖子需要一個CSV:
class Post
def to_csv(options = {})
CSV.generate(options) do |csv|
author.each do |x|
csv << [x]
end
end
end
end
Post.first.to_csv
注意從def self.to_csv
到def to_csv
的更改,使其成為實例方法而不是類方法。 另外[x]
而不是x
因為csv <<
需要一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.