Rails 3 Contact Form, undefined method?

混江龙づ霸主 提交于 2019-12-11 16:26:33

问题


I'm building a contact form in Rails 3 using this Railscast: http://railscasts.com/episodes/326-activeattr?view=asciicast

I know that the only thing I'm doing wrong is filling out where the message should be sent. I used the following code to send the message:

mail(:to => "me@myemail.com") 

However, this doesn't seem to work, because everytime I submit the form, I get this error:

NoMethodError in MessagesController#create

undefined method `mail' for #<MessagesController:0x00000103734bd8>

Application Trace | Framework Trace | Full Trace
app/controllers/messages_controller.rb:10:in `create'

What should I replace this line with to send the message?

messages_controller.rb

class MessagesController < ApplicationController

  def new
    @message = Message.new
  end

  def create
    @message = Message.new(params[:message])
    if @message.valid?
      UserMailer.contact_message(@message).deliver
      redirect_to root_url, notice: "Message sent! Thank you for contacting us."
    else
      render "new"
    end
  end

end

user_mailer.rb

class UserMailer < ActionMailer::Base

def contact_message(message)
@message = message
mail(:to => "myemail@mymail.com", :subject => "New Message")
end

end

setup_mail.rb

ActionMailer::Base.smtp_settings = {
:address              => "smtp.gmail.com",
:port                 => 587,
:domain               => "mywebsite.com",
:user_name            => "myemail",
:password             => "secret",
:authentication       => "plain",
:enable_starttls_auto => true
}

ActionMailer::Base.default_url_options[:host] = "localhost:3000"

回答1:


there's no object created on the mail variable on your controller. Actualy to user Mailer on rails you don't have to instantiate a variable just call you mailer with the method. Like:

YourMailer.send(params)

You can always go to rails guides to see how some stuff works: http://guides.rubyonrails.org/action_mailer_basics.html




回答2:


The Message object you're creating is just an object that can be used in a form with validations. You still need to actually create a Mailer object, and fill it with the name/email/message that you get from the @message object.

If you create a Mailer (see Episode 206 - Action Mailer), and you'd do something like this in your controller after creating a MessageMailer

def create
  if @message.valid?
    MessageMailer.contact_message(@message).deliver
    redirect_to root_url, notice: "Message sent! Thank you for contacting us."
  else
    render "new"
  end
end



回答3:


I just answered a similar question here: https://stackoverflow.com/a/17883328/307308

You are missing the from attribute in your mail method.

mail(:from => 'system@mymail.com', :to => "myemail@mymail.com", :subject => "New Message")


来源:https://stackoverflow.com/questions/11161364/rails-3-contact-form-undefined-method

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