问题
There are a lot of questions in SO about csv export in rails, but I didn't find one that addresses my problem. I'm trying to export all instances of a model in my rails app, and I was following Ryan Bates' RailsCast #362, but now I'm having problems with the generated CSV.
This is my index action in the model controller (@bookstore
is set up in another action, used in a before_filter
):
def index
@books = @bookstore.books
respond_to do |format|
format.html
format.csv { render text: @books.to_csv }
end
end
And I have this method in the Book Class (book.rb
):
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |book|
csv << book.attributes.values_at(*column_names)
end
end
end
The problem is that when I try to open /bookstores/1/books.csv I get this:
#<Book:0x007f7f755252a0>,#<Book:0x007f7f75524c38>,#<Book:0x007f7f755245f8>,#<Book:0x007f7f75523fe0>,#<Book:0x007f7f75523978>,#<Book:0x007f7f75523130>,#<Book:0x007f7f755227d0>,#<Book:0x007f7f75522190>,#<Book:0x007f7f75521b78>,#<Book:0x007f7f7552c2f8>
I don't know what's wrong, and have little experience with Ruby On Rails. Thanks!
回答1:
In the railscast, it says:
format.csv { send_data @products.to_csv }
Why don't you do that?
If that doesn't work, could you please try to collect your @books
object with the following code? I'm interested whether it will make a difference:
Book.where(:bookstore_id => @bookstore.id)
It shouldn't, but you seem to get an array of @books.each {|b| array << b.to_s}
somehow and I'm curious why.
回答2:
I was having the same problem. I figured out that my class method to_csv was not even getting called. I could delete it and get the same output.
I "solved" this problem by restarting my server. After that, to_csv started to get called correctly and things worked like they should.
The railscast episode 362 does mention restarting the server but does not make it clear that code wont work until you do.
Once we’ve restarted the server so that it picks up the csv library we should be able to view our CSV data.
[railscast episode 362] http://railscasts.com/episodes/362-exporting-csv-and-excel
回答3:
Had the same issue, followed this comment and it works now
http://railscasts.com/episodes/362-exporting-csv-and-excel?view=comments#comment_162272
来源:https://stackoverflow.com/questions/15295901/exporting-data-to-csv-in-rails-railscasts-362