-1

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

家庭控制器

    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 是零,任何建议

4

1 回答 1

0

这是我的 2 美分。

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

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

@email = Email.find(params[:id])由于我不知道您的型号,这可能会或可能不会起作用。(如其他评论中所述)

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

PS:当您不了解框架的基本知识时,接受在框架上进行编码不是一个好主意:)

于 2015-06-16T11:08:20.383 回答