如何使同一个方法可用于 Rails 中的多个模型?
对于一个名为 Email.rb 的模型,我有一个名为 new_todos 的方法,如下所示。
需要为 Call.rb、Postalcard.rb 等提供相同的方法。
我如何才能将其只编写一次并使其可供适当的模型使用,而不是在多个活动记录模型中剪切并粘贴这个精确的片段?
我怀疑它可以通过将模块放在 /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
For one Model called Email.rb, I have a method shown below called new_todos.
This same method needs to be made available for Call.rb, Postalcard.rb, etcetera.
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?
I suspect it could work by putting a module in the /lib folder, but I'm not exactly sure....thanks!
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所说,您可以创建一个模块并将其包含在您需要的地方。
As you say, you can create a module and include it where you need it.