[英]Using devise method 'current_user' in mailer
am relatively new to rails,i have been working with devise authentication gem for a while now,but my problem is,my app sends an email,with the firstname and lastname of the current user after a form is filled,but each time i try to send the email with the above stated parameters i get an error that says "undefined method current_user" my mailer looks like this,note:its a separate controller that controls it. 对Rails来说相对较新,我已经使用devise认证gem了一段时间,但是我的问题是,我的应用程序发送了一封电子邮件,填写了表单后显示了当前用户的名字和姓氏,但是每次我尝试要使用上述参数发送电子邮件,我会收到一条错误消息,指出“未定义的方法current_user”,我的邮件程序看起来像这样,请注意:它是一个单独的控制器来控制它。
<table>
<tr>
<td>name</td><td><%= current_user.firstname %><%=current_user.firstname %></td>
<tr>
<td>phone no.</td><td><%= current_user.phone %></td>
</tr>
<tr>
<td>location</td><td><%= @device.location %></td>
</tr>
<tr>
<td>device type</td><td><%= @device.device_type %></td>
</tr>
<tr>
<td>brand</td><td><%= @device.brand %></td>
</tr>
</table>
my controller action is this 我的控制器动作是这样
def create
@user=current_user
@device = Device.new(device_params)
if @device.save
DeviceMailer.send_device.deliver
flash[:notice] = 'Request sent successfully,you will be
contacted shortly' else flash[:error] ='Request not sent,check details and sendagain' render 'new' end 很快就联系上了” else flash [:error] ='请求未发送,请检查详细信息并再次发送'渲染'新'端
end
current_user
is a method that is available only to views and controllers. current_user
是仅对视图和控制器可用的方法。 If you want to use it in a mailer or model, it will have to be explicitly used as an argument for the mailer method. 如果要在邮件程序或模型中使用它,则必须将其显式用作邮件程序方法的参数。
Inside the controller create method: 在控制器内部的create方法:
DeviceMailer.send_device(current_user, @device).deliver
Mailer method: 邮寄方式:
def send_device(user, device)
@user = user
@device = device
# More code as needed
end
Mailer view: 邮件视图:
<table>
<tr>
<td>name</td>
<td><%= @user.firstname %><%= @user.firstname %></td>
</tr>
<tr>
<td>phone no.</td><td><%= @user.phone %></td>
</tr>
<tr>
<td>location</td><td><%= @device.location %></td>
</tr>
<tr>
<td>device type</td><td><%= @device.device_type %></td>
</tr>
<tr>
<td>brand</td><td><%= @device.brand %></td>
</tr>
</table>
current_user is set when you login. 登录时设置current_user。 In order to force the user to login before the user can execute a controller action you need to have the following line at the top of your controller:
为了在用户执行控制器操作之前强制用户登录,您需要在控制器顶部具有以下行:
before_action :authenticate_user!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.