在我尝试创建一些数据的可下载 csv 时,我遵循了这个 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 中添加了 require 'csv'。
但是,当我转到 admin/users.csv 并下载文档时,我只会得到 1 行类似“#User:0x851d030”的条目,而不是我想要的数据。我哪里搞砸了?