[英]In rails, given an array of objects, how can I output a CSV list instead of to_json?
If I do: 如果我做:
Contact.select('email').first(1000).to_json
I get a JSON response with emails... How can I get just a CSV of emails? 我收到电子邮件的JSON响应...如何仅获得电子邮件的CSV? XXX@.com, XXX@.com
XXX @ .com,XXX @ .com
I'm trying to do this from rails console. 我正在尝试从Rails控制台执行此操作。
Thanks 谢谢
Contact.select('email').map(&:email).join(", ")
You can install this plugin to have the to_csv
method. 您可以安装此插件以使用
to_csv
方法。 Or you can implement it yourself. 或者,您也可以自己实施。
I would vote for the prior, because if you'll need to print out names instead of emails you should implement the escaping as well, and this would be there for you by the plugin. 我会投票赞成,因为如果您需要打印出姓名而不是电子邮件,则也应该实现转义,并且插件将为您提供转义。
Update: 更新:
Oh I have not realized that you need only the mails, with this plugin you could do the following: 哦,我还没有意识到您只需要邮件,使用此插件,您可以执行以下操作:
@emails = Contact.select('email').first(1000).map(&:email)
respond_to do |format|
format.html
format.xml { render :xml => @emails }
format.csv { send_data @emails.to_csv }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.