[英]How can I make the same method available to multiple models in Rails?
For one Model called Email.rb, I have a method shown below called new_todos. 对于一个名为Email.rb的模型,我有一个下面显示的名为new_todos的方法。
This same method needs to be made available for Call.rb, Postalcard.rb, etcetera. 需要使Call.rb,Postalcard.rb等具有相同的方法。
Rather than cutting and pasting this exact snippet across multiple Models of Active Records, how can I have it written just once and make it available to the appropriate Models? 与其在多个Active Records模型之间剪切并粘贴这个精确的片段,我如何只编写一次并将其提供给适当的Models?
I suspect it could work by putting a module in the /lib folder, but I'm not exactly sure....thanks! 我怀疑可以通过将模块放在/ lib文件夹中来工作,但是我不确定...。谢谢!
def new_todos
Contact.campaign_id_is(self.campaign_id).each do |contact|
todo = Todo.new
todo.contact_id = contact.id
todo.user_id = contact.user_id
todo.asset = self.class.name
todo.asset_id = self.id
todo.original_date = contact.date_entered + self.days.days
todo.current_date = todo.original_date
todo.save
end
end
As you say, you can create a module and include it where you need it. 如您所说,您可以创建一个模块并将其包含在需要的位置。
#lib/todo_extension.rb
module TodoExtension
def new_todos
...
end
end
# call.rb, postalcard.rb...
include TodoExtension
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.