How can I make the same method available to multiple models in Rails?

家住魔仙堡 提交于 2020-01-01 00:49:12

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/4116811/how-can-i-make-the-same-method-available-to-multiple-models-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!