Ruby 郵箱激活功能

a1345774000 · August 25, 2021 · Last by PaulChan1995 replied at August 30, 2021 · 540 hits

現在的代碼只能發送郵件,我想點擊發送出去郵件的鏈接的時候再回到程序當中有什麽好的建議嗎,發送出去的鏈接應該怎麽填寫我也不是很清楚。

發送郵件的代碼

def temporary
    if request.post?
      @user = Client.new
      @user.dp_no = @user.token
      @user.client_adress = params[:email]
      @user.update_date = Time.new
      @user.create_date = Time.new
      @user.del_flg = 1
      @user.save
      MailVerifyMailer.welcome_email(@user).deliver_now
    end  
  end  

想點擊郵件回到的方法

def verification
   @user = Client.find_by(dp_no: value)
   update_params = {
     "del_flg" => false,
     "update_date" => Time.new
     }
   @user.update(update_params)
   flash[:success] = "Your account is now activated."
   redirect_to '/index'
 end

郵件模板

<h3>Welcome to daihatsu-member auth : <%= @user.client_adress %></h3>
    <p>
      You have successfully signed up to daihatsu-wifi
      your username is: <%= @user.client_adress%><br>
      your token is:<%= @user.dp_no%><br>
    </p>
    <p>
      To login to the site, please click this link : <%= link_to "here", "http://0.0.0.0:3000/activations/#{@user.dp_no}", method: :post %>
    </p>
    <p>Thanks for joining and have a great day!</p>

我想詢問一下怎麽能回到 verification 方法 模板裏的 url 應該怎麽填寫 感謝

路由映射下到对应 action。然后把设计的路径放进去就可以了吧

Reply to lewislinlin

這個路徑怎麽設計才能對應到 action 啊

Reply to a1345774000

你不是在 route 里面定义过路由么?

Reply to a1345774000

verification

这个方法在 router.rb 咋定义的?

link_to method: :post 依赖 Rails ujs,是只能在 Rails view 里面使用的辅助方法。邮件内容在邮件客户端打开,没有加载 rails ujs 的前端库,不能使用。

通常做法是在邮件里写一个对应 get 的页面地址,在这个地址内让用户手动或者用 js 自动提交 post 请求。

Reply to gakki

get '/activations/:token' => 'index#verification' 這麽定義的 不好意思回復的有些晚了

Reply to Rei

了解 我去查詢一下 js 自動提交

Reply to a1345774000

简单方法是先用 form_with 生成一个常规 Rails form(带有 csrf token),然后页面内一段 js 提交:

<script>document.getElementById('form-id').submit()</script>

搜 js 提交可能会查到纯 ajax 然后碰到 csrf token 的问题。

Reply to Rei

题外话 dhh 那边搞了个 https://github.com/rails/request.js 可以自动拿 meta 的 csrf token

Reply to jicheng1014

这个库超赞,不仅解决了 csrf token 问题,还能指定返回类型,配合 turbo 非常不错

Reply to jicheng1014

我现在用着 rails-ujs 带的 Rails.ajax 方法,看上去以后 rails-ujs 会被抛弃,到时就转 request.js。

Reply to v2up

是的 感觉这个主要就是给 hotwired 套件用的

Reply to Rei

可以看看mrujs

devise 也有相应功能,你可以参考它的路由设计

You need to Sign in before reply, if you don't have an account, please Sign up first.