需要使用电子邮件作为params,rails从find_by返回用户对象

时间:2017-10-18 04:09:31

标签: ruby-on-rails

我想将整个对象及其属性返回给我的变量,但它似乎只是返回电子邮件。

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
...

views / usermailer / account_activations.html.erb

中的服务器错误
 ActionView::Template::Error (No route matches {:action=>"edit", :controller=>"account_activations", :email=>"example2005@railstutorial.org", :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) %>

我不确定如何构建我的控制器操作,以便我可以包含路由的ID?

编辑添加User.rb和路由

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

1 个答案:

答案 0 :(得分:2)

在文件{9}中的第9行

请添加views/usermailer/account_activations.html.erb作为参数:

id

编辑:

  

为什么我需要这个?

你需要它,因为你使用Rails魔法:<%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email, id: @user.id) %> 此行为您生成路线。这些路由需要resources :account_activations, only: [:edit]作为参数。如果你去http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing 您可以看到生成的路线示例(您也可以在终端中运行:id以查看实际路线)。
在那里,您看到bin/rake routes路由需要:edit参数 如果您自己编写路线而不使用:id,则可以使用除:resources之外的其他参数来识别记录。