Reputation: 67
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.
<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
end
Upvotes: 0
Views: 1524
Reputation: 802
current_user is set when you login. 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!
Upvotes: 0
Reputation: 1854
current_user
is a method that is available only to views and controllers. 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:
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>
Upvotes: 2