在我尝试创建一些可下载的某些数据的csv时,我遵循了this railscast.
我有一个用户模式的管理页面,位于views / admin / users.html.erb
中在我的管理员控制器中,我有:
def users
@users = User.all
respond_to do |format|
format.html
format.csv {send_data @users.to_csv}
format.xls {send_data @users.to_csv(col_sep: "\t")}
end
end
在我的用户模型中:
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << ["First Name","Last Name","Street","City","State","Zip","Company Name","Company Phone","Company Street","Company City","Company State","Company Zip","Deals Viewed","Deals Clicked Invest On","Deals Invested In","Amount Invested in Hedge Funds","Amount Invested in PPM"]
all.each do |user|
csv << [user.first_name, user.last_name, user.p_street, user.p_city, user.p_state, user.p_zip, user.c_name, user.c_phone, user.c_street, user.c_city, user.c_state, user.c_zip, user.clicks.count, user.investments.where(:status => "Interested").count, user.u.investments.where(:status => "Invested").count, user.amount_invested_2, user.amount_invested_3]
end
end
end
我向application.rb添加了'csv'。
然而,当我转到admin / users.csv并下载文档时,我只得到1行条目,如'#User:0x851d030',而不是我想要的数据。我在哪里搞砸了?
答案 0 :(得分:1)
你没搞砸。你跟着railscast,它碰巧不适合你。我遇到了同样的问题。
我查看了“评论”标签,看看其他人是否有同样的问题。至少有一个人做过。 (帖子:http://railscasts.com/episodes/362-exporting-csv-and-excel?view=comments#comment_160703)
简而言之,您需要更改:
format.csv {send_data @users.to_csv}
取而代之的是
format.csv {send_data User.to_csv}