save_with_captcha is nil in controller

62 views Asked by At

I have home controller and trying to update the field of a table of different controller.

Home controller

    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

So I am trying to create new field of Email Model in my home controller but when I click save it throws this error...

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'

I have email model with defined validations which is like this

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"

end

So I do not understnd why this save_simple_captcha is nil, any suggestions

1

There are 1 answers

0
Mr H On

Here my 2 cents.

Remember HTTP is stateless. You have defined @email in the index, you have gotten to the esave after page has been refreshed so @email is no longer available. ( Controller is a bit different that straight Ruby Class that get instantiated and variables can be tossed around )

You HAVE TO instantiate the @email for the method your are in. I don't know what is in your Model so I can just guess the rest.

This @email = Email.find(params[:id]) might or might not work as I don't know your model. ( as mentioned in other comments )

Put your model here too. We might be able to help you out.

PS: It is not a good idea to accept to code on a framework when you don't know a very basic of it :)