如何将方法应用于 ActiveRecord 对象的集合 [英] How do you make a method apply to a collection of ActiveRecord objects
本文介绍了如何将方法应用于 ActiveRecord 对象的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,如果我想将一个方法应用于一组 ActiveRecord 对象,我必须像这样构造调用:
Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:
messages = Message.find(:all)
csv = Message.to_csv(messages)
如何定义方法,使其结构如此?
How can I define the method so it's structured like so?
messages = Message.find(:all)
csv = messages.to_csv
这是当前的型号代码:
require 'fastercsv'
class Message < ActiveRecord::Base
def Message.to_csv(messages)
FasterCSV.generate do |csv|
csv << ["from","to", "received"]
for m in messages
csv << [m.from,m.to,m.created_at]
end
end
end
end
推荐答案
以下内容将对包含在消息数组中的所有实例调用 to_csv.
The following will call to_csv on all instances included in the messages array.
messages = Message.find(:all)
csv = messages.map { |message| message.to_csv }
在 Rails、Ruby 1.9 或 Symbol#to_proc 中,您也可以通过其他方式将其缩短为:
In Rails, in Ruby 1.9 or with Symbol#to_proc available through other means, you can also shorten it to:
csv = messages.map(&:to_csv)
当您想要进行更复杂的操作时,较长的形式很有用:
The longer form is useful when you want to make a more complex operation:
csv = messages.map { |message|
if message.length < 1000
message.to_csv
else
"Too long"
end
}
这篇关于如何将方法应用于 ActiveRecord 对象的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文