0

在我尝试创建一些数据的可下载 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”的条目,而不是我想要的数据。我哪里搞砸了?

4

1 回答 1

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}

于 2013-05-03T16:30:09.627 回答