Rails在分隔目录中的邮件程序视图

我有一个小的组织问题,在我的应用程序中我有3个邮件程序User_mailer,prduct_mailer,some_other_mailer,所有这些都将他们的视图存储在app / views / user_mailer中……

我想在/ app / views /中设置一个名为mailers的子目录,并将所有文件放在user_mailer,product_mailer和some_other_mailer文件夹中。

谢谢,

我非常赞同这种组织策略!

从Nobita的例子中,我通过以下方式实现了:

class UserMailer < ActionMailer::Base default :from => "whatever@whatever.com" default :template_path => '**your_path**' def whatever_email(user) @user = user @url = "http://whatever.com" mail(:to => user.email, :subject => "Welcome to Whatever", ) end end 

这是梅勒特有的但不是太糟糕!

您应该使用默认值创建一个ApplicationMailer类,并从邮件中inheritance它:

 # app/mailers/application_mailer.rb class ApplicationMailer < ActionMailer::Base append_view_path Rails.root.join('app', 'views', 'mailers') default from: "Whatever HQ " end # app/mailers/user_mailer.rb class UserMailer < ApplicationMailer def say_hi(user) # ... end end # app/views/mailers/user_mailer/say_hi.html.erb Hi @user.name! 

这个可爱的模式使用与控制器相同的inheritance方案(例如ApplicationController < ActionController::Base )。

我在3.1中有一些运气

 class UserMailer < ActionMailer::Base ... append_view_path("#{Rails.root}/app/views/mailers") ... end 

在template_root和RAILS_ROOT上获得了弃用警告

如果您碰巧需要一些非常灵活的东西,inheritance可以帮助您。

 class ApplicationMailer < ActionMailer::Base def self.inherited(subclass) subclass.default template_path: "mailers/#{subclass.name.to_s.underscore}" end end 

您可以将模板放在任何位置,但必须在邮件程序中指定它。 像这样的东西:

 class UserMailer < ActionMailer::Base default :from => "whatever@whatever.com" def whatever_email(user) @user = user @url = "http://whatever.com" mail(:to => user.email, :subject => "Welcome to Whatever", :template_path => '**your_path**', ) end end 

有关详细信息,请查看2.4 Mailer Views 。