如何在Rails中为多个模型提供相同的方法? [英] How can I make the same method available to multiple models in Rails?

查看:129
本文介绍了如何在Rails中为多个模型提供相同的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个名为Email.rb的模型,我有一个下面显示的名为new_todos的方法.

For one Model called Email.rb, I have a method shown below called new_todos.

Call.rb,Postalcardcard.rb等必须使用相同的方法.

This same method needs to be made available for Call.rb, Postalcard.rb, etcetera.

除了将确切的代码片段剪切并粘贴到多个Active Records模型之外,我如何只编写一次并将其提供给适当的模型?

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?

我怀疑可以通过将模块放在/lib文件夹中来工作,但是我不确定....谢谢!

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

推荐答案

正如您所说,您可以创建一个模块并将其包含在需要的位置.

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

这篇关于如何在Rails中为多个模型提供相同的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆