【问题标题】:save_with_captcha is nil in controllersave_with_captcha 在控制器中为零
【发布时间】:2023-03-17 18:45:01
【问题描述】:

我有家庭控制器并尝试更新不同控制器的表的字段。

家庭控制器

    class HomeController < ApplicationController

    before_action :user_params, only: [:index]

    def index
      @email = Email.new(user_params)
    end

    def contact
    end

     def faq
     end

    def team
    end

    def privacy
    end

    def esave
    if !user_params.nil?
      if @email.save_with_captcha
        flash[:notice] = "Thank you for registering you email address"
        redirect_to :action => 'index'
      else
        render 'esave'
      end
    end
     end

     def user_params
      params.require(:email).permit(:email, :captcha, :captcha_key) if  params[:email]
   end

 end

所以我试图在我的家庭控制器中创建电子邮件模型的新字段,但是当我点击保存时,它会抛出这个错误......

App 24078 stderr: Completed 500 Internal Server Error in 3ms
App 24078 stderr: 
App 24078 stderr: NoMethodError (undefined method `save_with_captcha' for nil:NilClass):
App 24078 stderr:   app/controllers/home_controller.rb:37:in `esave'

我有一个带有定义验证的电子邮件模型,就像这样

class Email < ActiveRecord::Base
apply_simple_captcha :message => "The secret Image and code were different", :add_to_base => true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/ , :message => "Invalid Format"

结束

所以我不明白为什么这个 save_simple_captcha 是 nil,任何建议

【问题讨论】:

  • 你必须定义@email @email = Email.find(params[:id])之类的东西
  • 但是我已经在 Index 方法中定义了电子邮件,但是 user_params 验证呢?
  • 您也已经在esave 方法中定义了它。因为它是一个实例方法,你需要为每个实例方法定义实例对象
  • 你的意思是电子邮件,但我没有在 esave 中定义任何内容
  • 是的,错误也是如此。

标签: ruby-on-rails ruby-on-rails-4 simplecaptcha


【解决方案1】:

这是我的 2 美分。

记住 HTTP 是无状态的。您在索引中定义了@email,在页面刷新后您已经到达esave,因此@email 不再可用。 (Controller 与直接实例化的 Ruby 类有点不同,变量可以被扔掉)

您必须为您所在的方法实例化 @email。 我不知道你的模型中有什么,所以我只能猜测其余的。

这个@email = Email.find(params[:id]) 可能会也可能不会,因为我不知道你的型号。 (在其他 cmets 中提到)

把你的模型也放在这里。我们或许可以为您提供帮助。

PS:如果您不了解框架的基本知识,则接受在框架上编写代码不是一个好主意:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2018-06-26
    • 2021-05-30
    • 2012-04-23
    • 2022-08-19
    相关资源
    最近更新 更多