Rails:表单字段未传递给方法

时间:2015-09-23 21:41:28

标签: ruby-on-rails forms

我正在对用户进行电话验证。我将用户带到他们看到用户详细信息的页面和用于验证电话的按钮。

当他们点击按钮时,他们会收到带有验证码的短信(这可以通过Twilio完成),并且模型会通过phone_verification_code更新(这也有效)。请参阅UsersController中的方法“verify”。

当用户在http://localhost:3000/users/12/verify页面上时。他们看到一个“验证电话”的按钮,我通过它触发控制器中的“confirm_code”方法。

这里有两个问题。 1.表单字段预先填充了phone_verification_code。我的意思是让用户在获取文本后手动输入。 2.我总是收到“此时无法验证电话”的消息。我似乎没有正确地将phone_verification_code传递给控制器​​中的“confirm_code”方法。

我需要改变什么?

应用程序/视图/用户/ verify.html.erb

<%= form_for @user, :url => { :action => "confirm_code" }  do |f|  %>
    <%= f.text_field :phone_verification_code %>
    <%= f.submit "Verify phone", class: "btn btn-primary" %>
 <%end%>

用户模型

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable, :timeoutable

  def confirm_pin(entered_pin)
    update(phone_verified: true) if self.phone_verification_code == entered_pin
  end 

end

UserController中

class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def show
    begin
      @user = User.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error "Attempt to access an invalid user: #{params[:id]}"
      redirect_to store_url, notice: "Attempt to access an invalid user: #{params[:id]}"
    else
      respond_to do |format|
        format.html # show html.erb
        format.json { render json: @user }
      end
    end
  end

  def verify
    @user = User.find(params[:id])
    @user.phone_verification_code = rand(0000..9999).to_s.rjust(4, "0")
    @user.save
    SendTexts.send_verification_code(@user.phone_verification_code)
  end

  def confirm_code
    @user = User.find(params[:id])
    @user.confirm_pin(params[:phone_verification_code])
    if @user.phone_verified == true
      redirect_to store_url, notice: "Phone number verified"
    else
      redirect_to store_url, notice: "Could not verify phone at this time"
    end
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      @user = nil
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params[:user]
    end

end

1 个答案:

答案 0 :(得分:1)

对于您的第一个问题,请更改text_field,如下所示

<%= f.text_field :phone_verification_code, :value => nil %>

这可以避免预先填充text_field

phone_verification_code

对于你的第二个问题,你总是得到&#34;此时无法验证电话的原因&#34;是因为您将 错误参数 传递给confirm_pin方法,因此phone_verified 永远不会设置为true

<强> 解决方案:

当您查看日志中生成的params时,您会在用户哈希中看到:phone_verification_code 。因此,将@user.confirm_pin(params[:phone_verification_code])方法中的这一行confirm_code更改为@user.confirm_pin(params[:user][:phone_verification_code])