2013-07-06 5 views
0

메일러를 구현해야하므로 간단한 양식을 작성하려고합니다.ActionMailer 및 ActiveModel

class ContactusController < ApplicationController 
    def index 
     @contact_us = Contactus.new 
    end 

    def new 
     redirect_to(action: 'index') 
    end 

    def create 
     @contact_us = Contactus.new(params[:contactus]) 
     if @contact_us.deliver 
     flash[:notice] = "Thank-you, We will contact you shortly." 
     else 
     flash[:error] = "Oops!!! Something went wrong. Your mail was not sent." 
     end 
     render :index 
    end 
end 

내가 ActiveModel를 사용하여 데이터를 저장하지 않기 때문에 :

class Contactus 
    extend ActiveModel::Naming 
    include ActiveModel::Conversion 
    include ActiveModel::Validations 
    include ActionView::Helpers::TextHelper 
    attr_accessor :name, :email, :message 

    validate :name, 
     :presence => true 

    validates :email, 
     :format => { :with => /\b[A-Z0-9._%a-z\-][email protected](?:[A-Z0-9a-z\-]+\.)+[A-Za-z]{2,4}\z/ } 

    validates :message, 
     :length => { :minimum => 10, :maximum => 1000 } 

    def initialize(attributes = {}) 
     attributes.each do |name, value| 
      send("#{name}=", value) 
     end 
    end 

    def deliver 
     return false unless valid? 
    mail(
     :to => "[email protected]", 
     :from => %("#{name}" <#{email}>), 
     :reply_to => email, 
     :subject => "Website inquiry", 
     :body => message, 
     :html_body => simple_format(message) 
     ) 
    true 
end 

def persisted? 
    false 
end 
end 

모든 것이 잘 작동

나는 컨트롤러를 만들었습니다. 라우팅은 좋은, 유효성 검사가 작동하지만 내가 할 수있는 유일한 오류는 다음과 같습니다 undefined method mail for #<Contactus:0x007f9da67173e8>

내가 이름 CONTACTUS하고 있다는 점에서 사용자 모델 코드 메일러를 만들려고하지만, 내가 다음과 같은 오류 있어요 : private method new used

을 ActiveModel에서 ActionMailer 기능을 사용하려면 어떻게해야합니까?

답변

2

이 메일러를 설정하는 방법에 대한 좀 더 자세한 정보가이 명령을 실행하십시오 : 당신은 설정이 있으면

은 메일러 클래스는 ContactUs에서 다음과 같이 사용할 수 있습니다

rails generate mailer ContactMailer 

라는 이름의 파일에 다음을 추가 app/mailers/contact_mailer

class ContactMailer < ActionMailer::Base 
    default from: #{from_email} 

    def contact_mail(contact) 
    @contact = contact 
    mail(to: #{email}, subject: #{Whatever your subject would be}) 
    end 
end 

ActionMailer는보기를 사용하여 메시지의 레이아웃을 렌더링합니다. documentation을 확인했지만 여기에서 사용중인 html_body 옵션에서 아무 것도 찾을 수 없습니다. 어쩌면 이것을 제거하고 body: simple_format(message)을 사용하거나 템플릿 app/views/mailers/contact_mailer/contact_mail.html.erb을 만들고 메시지를 직접 입력하십시오. 당신은을 인스턴스 변수로 만들었습니다. 따라서 그러한 템플릿을 만들면 객체의 모든 사용 가능한 속성에 액세스 할 수 있으므로 원하는 경우 조금 더 사용자 정의 할 수 있습니다.

다른 노트에

... 난 당신이 여기에 index 행동에 new 조치를 전달하고 있는지 조금 걱정. RESTful 접근법을 변경해야하는 정말 좋은 이유가 있습니까? 10 회 중 9 번, private method called 또는 다른 이상한 오류가 발생했을 때 시스템을 속이려고 할 때가있었습니다. 새 Contactus 개체를 만들기 위해 new 작업을 다시 할당하면 문제가 해결됩니까? 이러한 설정

내 고용주의 표준 SMTP 설정에 대한

업데이트가 밖으로 최고의 수 있지만 여기에 내가 지금까지 한 일이다하지 않을 수 있습니다.내 environments/development.rb에서 environments/production.rb

config.action_mailer.raise_delivery_errors = false 
config.action_mailer.perform_deliveries = true 
config.action_mailer.delivery_method = :smtp 
config.action_mailer.smtp_settings = { 
    :hash => 'of', 
    :mail => 'client', 
    :smtp => 'settings' 
} 

내가 같은 블록을 복사하지만 내 environments/test.rb에서

config.action_mailer.raise_delivery_errors = true 

로 첫 줄을 대체 내에서 나는 위의 어느 것도 추가하지 않습니다. 대신이 줄을 추가합니다.

config.action_mailer.delivery_method = :test 

하지만 그 이유는 전자 메일이 내 RSpec 테스트에서 보내지는 것을 테스트하기 때문입니다.

environment.rb에서 설정이 어떻게 표시되는지 잘 모르겠지만 ActionMailer를 통해 구성하고 있는지 확인하고 싶을 수 있습니다. 당연히 이러한 변경 작업 후에 앱을 다시 시작하고 인증 문제가 계속 발생하는지 확인하십시오. 특정 인증 문제

내 개인 SMTP 설정은 Gmail을 통해 인증에 대한

, 그래서 이러한 파일 내 설정은 다음과 쌍을 포함

:address => 'smtp.gmail.com', 
:port => #{port_number}, 
:domain => #{our_email_domain}, 
:authentication => 'plain', 
:enable_starttls_auto => true 

portdomain 당신을 찾고보십시오. 자체 도메인이있는 비즈니스에서이 작업을 수행하지 않으면 Google 검색으로 충분합니다. 비밀번호가 올바르게 해석되지 않으면 authenticationsmarttls 설정이 도움이됩니다. => "[email protected]"에 :

+0

나는 새로운 작업 문제에 관해서는 확실히 시도 할 것입니다. 메일러 클래스의 객체를 만들고 있지만 실제로는 construtor가 없습니다. 거기에 문제가 있었다 : –

+0

그랬 으면 좋겠다;) –

+0

지금은 좀 앞으로지만, 지금은 매우 이상한 errro Net :: SMTPAuthenticationError 비록 내가 enviornment.rb 어떤 실마리에 ActionMailer :: Base.smtp_settings에 옳은 것들을 입력했지만 그거에 대해서 –

1

ActionMailer::Base에서 상속받은 app/mailerscreate a separate class이 있어야합니다. 이 수업에서는 mail 방법으로 전화 할 수 있습니다. 클래스에서 mail으로 바로 전화 할 수 없습니다. 당신의 우편물을 생성하기 위해,

ContactMailer.contact_mail(self).deliver 
+0

내가 ActionMailer :: Base.mail ( 을 사용 => % ("# {이름}"<#{email}>)에서, : REPLY_TO => 이메일, : 제목 => "웹 사이트 문의", : body => 메시지, : html_body => simple_format (메시지) ) 성공했는데 왜 그래도 메일을받지 못했습니다. –

+0

좀 더 단계별로 현명하게 수행 할 수 있습니까? 여기 미안 초보자 : ( –