ruby-on-railsrubyservice-object

undefined method `insert' for RegistrationInsert:Class


I'm trying to call a method I defined in registration_insert.rb from my controller but I keep getting the following error:

undefined method `insert' for RegistrationInsert:Class

How do I correctly call the insert method?

File Structure (all under /app)

-controllers

---------registrations_controller.rb

-registrations

---------registration_insert.rb

registrations_controller.rb:

 def create
    @registration = Registration.new(registration_params)
    RegistrationInsert.insert(registration_params)


    respond_to do |format|
      if @registration.save
        format.html { redirect_to @registration, notice: 'Registration was successfully created.' }
        format.json { render :show, status: :created, location: @registration }
      else
        format.html { render :new }
        format.json { render json: @registration.errors, status: :unprocessable_entity }
      end
    end
  end

registration_insert.rb

module RegistrationInsert 
    def insert(registration)
        #method code
    end
end

Edit: Changed class to module and it gives me this error:

undefined method `insert' for RegistrationInsert:Module


Solution

  • Maybe you need just RegistrationInsert.new.insert?

    P.S. Please consider to make RegistrationInsert a class, not module. Classes are better for service objects realization.

    P.P.S. If you want RegistrationInsert.new, then add self. before the method:

    module RegistrationInsert 
      def self.insert(registration)
        #method code
      end
    end