Lee Eather
Lee Eather

Reputation: 355

Need to return user object from find_by using email as params, rails

I want to return the entire object and its attributes to my variable but its seems to only be returning the email.

Userscontroller

....
def resend_act_create
  @user = User.find_by(email: params[:user][:email])
  if @user
    @user.send_activation_email
    flash[:info] = "Please check your email to activate your account."
    redirect_to root_url
  else
    flash[:warning] = "Could not find email in database"
    render 'account_activations/new'
  end
end
...

server error in views/usermailer/account_activations.html.erb

 ActionView::Template::Error (No route matches {:action=>"edit", :controller=>"account_activations", :email=>"[email protected]", :id=>nil} missing required keys: [:id]):
 6: Welcome to the Sample App! Click on the link below to activate your account:
 7: </p>
 8:
 9: <%= link_to "Activate", edit_account_activation_url(@user.activation_token,
10:                                                     email: @user.email) %>

I am not sure how to build my controller action so I can include the id for the route?

EDIT Add User.rb and routes

class User < ApplicationRecord

....
def send_activation_email
  UserMailer.account_activation(self).deliver_now
end
....

routes.rb

....
resources :account_activations, only: [:edit]

UserMailer.rb

def account_activation(user)
  @user = user
  mail to: user.email, subject: "Account activation"
end

Upvotes: 0

Views: 644

Answers (1)

Holger Frohloff
Holger Frohloff

Reputation: 1705

In line 9 in your file views/usermailer/account_activations.html.erb

Please add the id as argument:

<%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email, id: @user.id) %>

Edit:

Why do I need this?

You need it, because you use Rails magic: resources :account_activations, only: [:edit] This line generates the routes for you. These routes require the :id as parameter. If you go to http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing You can see the generated routes for an example (you can also run bin/rake routes in your terminal to see your actual routes).
There you see, that the :edit route needs the :id parameter.
If you wrote your route by yourself, without using :resources, you could use another param than :id for identifying the record.

Upvotes: 2

Related Questions