【发布时间】:2015-02-27 21:45:35
【问题描述】:
我正在尝试实现电子邮件功能,以便当有人注册时他们会收到电子邮件。我正在关注本指南:http://guides.rubyonrails.org/action_mailer_basics.html
但我得到了错误:
TypeError in UsersController#create
can't convert String into Hash
application_mailer.rb:
class ApplicationMailer < ActionMailer::Base
default "from@example.com"
layout 'mailer'
end
user_mailer.rb:
class UserMailer < ApplicationMailer
default from: 'notifications@example.com'
def welcome_email(user)
@user = user
@url = 'http://localhost:3000/users/login'
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
end
end
views/user_mailer/welcome_email.html.erb:
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Welcome to example.com, <%= @user.name %></h1>
<p>
You have successfully signed up to example.com,
your username is: <%= @user.login %>.<br>
</p>
<p>
To login to the site, just follow this link: <%= @url %>.
</p>
<p>Thanks for joining and have a great day!</p>
</body>
</html>
views/user_mailer/welcome_email.txt.erb
Welcome to example.com, <%= @user.name %>
===============================================
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
To login to the site, just follow this link: <%= @url %>.
Thanks for joining and have a great day!
还有users_controller中的create方法:
def create
@user = User.new(user_params)
if @user.save
# login is achieved by saving a user's 'id' in a session variable,
# accessible to all pages
UserMailer.welcome_email(@user).deliver_later
session[:user_id] = @user.id
redirect_to films_path
else
render action: "new"
end
end
用户控制器中的用户参数:
def user_params
params.require(:user).permit(:password, :password_confirmation, :role, :first_name, :last_name, :house_no, :street, :town, :postcode, :email, :date_of_birth)
end
完全错误:
TypeError in UsersController#create
can't convert String into Hash
Extracted source (around line #0):
Rails.root: C:/Sites/Thor/Under Construction/ThorCinema/new/Lab/ThorCinema
Application Trace | Framework Trace | Full Trace
app/mailers/application_mailer.rb:2:in `<class:ApplicationMailer>'
app/mailers/application_mailer.rb:1:in `<top (required)>'
app/mailers/user_mailer.rb:1:in `<top (required)>'
app/controllers/users_controller.rb:33:in `create'
有人可以帮忙吗。
【问题讨论】:
-
您使用的是哪个 Rails 版本?如果您使用的是 rails 3,那么您不能传递
@user这样,您必须传递@user.id然后从您的邮件中加载用户。 -
我使用的是 Rails 4.2.0
-
你能显示
user_params,还有其余的错误。就像哪个数字确切提到该字符串不能转换为哈希 -
@Coderhs 我添加了
user_params和错误
标签: ruby-on-rails ruby ruby-on-rails-3 email methods