开发者

In rails, given an array of objects, how can I output a CSV list instead of to_json?

开发者 https://www.devze.com 2023-04-04 07:55 出处:网络
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? XXX@.com, XXX@.com

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? XXX@.com, XXX@.com

I'm trying to do this from rails console.

Thanks


Contact.select('email').map(&:email).join(", ")


You can install this plugin to have the to_csv method. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号