ActionMailer보기에서보기 도우미를 사용하는 방법은 무엇입니까?


227

app/helpers/annotations_helper.rbReportMailer보기 ( app/views/report_mailer/usage_report.text.html.erb) 에서 정의한 방법을 사용하고 싶습니다 . 어떻게해야합니까?

이 가이드를 기반으로 add_template_helper(helper_module)방법이 원하는 것을 할 수있는 것처럼 보이지만 사용 방법을 알 수는 없습니다.

(BTW, 메일러보기에서 다른 헬퍼 세트에 액세스 할 수있는 이유가 있습니까? 이것은 꽤 성가신 일입니다.)


답변:


324

이메일 관리에 사용하는 메일러 클래스에서 :

class ReportMailer < ActionMailer::Base
  add_template_helper(AnnotationsHelper)

  ...
end

4
이 경우에는 작동하지 않습니다 (Rails 3.2.8) : ApplicationController에 정의 된 메소드가 있으며 helper_method : my_helper_wannabe에 의해 헬퍼가되지만 "my_helper_wannabe"메소드는 메일러에서 사용할 수 없습니다.
Giang Nguyen

Rails 3에서 처리하는 방법은 아래 듀크의 답변을 참조하십시오.
Chris Peters

레일스에서 ​​작동 3.2.11
Jan

1
나는 이것이 Rails 4에 자동으로 포함되어야한다고 생각 했습니까? guides.rubyonrails.org/…
gabeodess

6
이것은 고대의 대답이지만 이것이 Rails 5.2에서 작동
했다는 것을 알려줍니다.

158

Rails 3에서는 ActionMailer 클래스의 맨 위에있는 helper 메소드를 사용하십시오.

helper :mail   # loads app/helpers/mail_helper.rb & includes MailHelper

한 Mailer에서만 필요하기 때문에 방금 블록을 전달했습니다.

helper do
  def host_url_for(url_path)
    root_url.chop + url_path
  end
end

(config.action_mailer.default_url_options를 설정해야합니다.)

(url_for를 사용하는 경우 : only_path => false를 전달하십시오)


3
이것은 작동하지만 ApplicationController에 이미 정의 된 헬퍼를 개별 ActionMailer 클래스로 다시 지정하는 것은 불편합니다. ActionMailer는 ActionController를 확장하여 공통 계층 구조에서 나옵니다. 더 많은 솔루션에 비해 레일에 대한 코멘트 ...의
robbie613

3
그리고 도우미가 네임 스페이스에 있다면helper :'namespace/mail'
Jonathon Batson

도우미가 네임 스페이스에 있으면 기호 대신 문자열 만 허용합니다.helper 'namespace/mail'
Pwnrar

2
Rails 5.2에서 작동합니다!
RousseauAlexandre

28

Rails 3의 모든 메일러 ( "응용 프로그램"도우미 설정) :

# config/application.rb:
...
config.to_prepare do
  ActionMailer::Base.helper "application"
end

공유 이메일 부분에 대한 최상의 답변. 감사!
Alexey Shein

2
사실이 아님 helper :application-Rails 4.2.1에서 잘 작동합니다.
steakchaser

에 대한 자체 이메일 템플릿에서도 제대로 작동합니다 devise. helper :application이 경우에는 작동하지 않습니다.
Sven R.

1
4.2.5.1에서 작동하지 않음- include ApplicationHelper작동
했음

23

Ruby on Rails 4의 경우 두 가지 작업을 수행해야했습니다.

(1) Duke가 이미 말했듯이 추가하려는 도우미가 UsersHelper예를 들어 추가하면

helper :users

유도에 ActionMailer클래스 (예 app/mailers/user_mailer.rb)

(2) 그 후에 새로운 오류가 발생했습니다.

ActionView::Template::Error (Missing host to link to! Please provide the :host
parameter, set default_url_options[:host], or set :only_path to true)

이 문제를 해결하려면 줄을 추가하십시오.

config.action_mailer.default_url_options = { :host => 'localhost' }

config/environments/*.rb파일에. 의 경우 프로덕션 헬퍼 생성 URL에 적합한 호스트로 config/environments/production.rb교체하십시오 localhost.


Q : # 2의 경우 메일보기에이 정보가 필요한 이유는 무엇입니까?

A : 일반보기는을 알 필요가 없으므로 host생성 된 모든 링크는 연결된 호스트에서 제공되므로 이메일에 표시되는 링크는 같은 호스트에서 제공되지 않습니다 ( hotmail.com또는에 연결하지 않는 한 gmail.com).


작성된 이름은 어떻습니까? User::ComposedHelper
Cyril Duchon-Doris


17

(이것은 오래된 질문이지만 Rails는 진화했기 때문에 Rails 5.2에서 나에게 맞는 것을 공유하고 있습니다.)

일반적으로 전자 메일의 제목 줄과 HTML을 렌더링 할 때 사용자 지정보기 도우미를 사용할 수 있습니다. 뷰 헬퍼가 app / helpers / application_helper.rb에있는 경우 다음과 같습니다.

module ApplicationHelper

  def mydate(time, timezone)
    time.in_time_zone(timezone).strftime("%A %-d %B %Y")
  end

end

도우미를 사용하는 동적 전자 메일 제목 줄과 템플릿을 만들 수 있지만 여기 에서 두 번째와 세 번째 줄에서 볼 수 있듯이 앱 / 메일러 /user_mailer.rb 에서 명시 적으로 ApplicationHelper를 사용하도록 Rails에 알려야 합니다. :

class UserMailer < ApplicationMailer

  include ApplicationHelper  # This enables me to use mydate in the subject line
  helper :application  # This enables me to use mydate in the email template (party_thanks.html.erb)

  def party_thanks
    @party = params[:party]
    mail(to: 'user@domain.com',
    subject: "Thanks for coming on #{mydate(@party.created_at, @party.timezone)}")
  end

end

이 두 줄은 잘 작동하므로 언급하십시오.

helper :application

add_template_helper(ApplicationHelper)

app / views / user_mailer / party_thanks.html.erb 의 이메일 템플릿 인 FWIW 는 다음과 같습니다.

<p>
  Thanks for coming on <%= mydate(@party.created_at, @party.timezone) %>
</p>

그리고 app / controller / party_controller.rb 컨트롤러는 다음과 같습니다

class PartyController < ApplicationController
  ...
  def create
    ...
    UserMailer.with(party: @party).party_thanks.deliver_later
    ...
  end
end

https://guides.rubyonrails.org/action_mailer_basics.html#using-action-mailer-helpers를 감안할 때 OP (@Tom Lehman) 및 @gabeodess에 동의해야합니다 . .


5

Rails4의 경우에는 다음과 같이합니다.

# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  add_template_helper ApplicationHelper
  ...
end

# app/mailers/user_mailer.rb
class AccountMailer < ApplicationMailer
  def some_method(x, y)
  end
end

add_template_helper어디서나 지정할 필요가 없습니다 .

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.