ruby-on-railsrubyrailsappslearn-ruby-on-rails

Instantiate a ruby class no initialize method but with attr_accesors?


The following code works but I don't understand why.

The Model: I have a Class called Contact that doesn't have an initialize method (i.e it inherits the initialize method from the default Object class).

class Contact
  include ActiveModel::Model
  attr_accessor :name, :string
  attr_accessor :email, :string
  attr_accessor :content, :string

  validates_presence_of :name
  validates_presence_of :email
  validates_presence_of :content
  ... 
end

The controller: I have a ContactsController with a 'create' method that instantiates the Contact class passing along some parameters through the 'secure_params' method.

class ContactsController < ApplicationController
   def new
     @contact = Contact.new
   end

   def create
      # THIS IS THE LINE THAT I DON'T UNDERSTAND
      @contact = Contact.new(secure_params)

      if @contact.valid?

         @contact.update_spreadsheet
         UserMailer.contact_email(@contact).deliver
         flash[:notice] = "Message sent from #{@contact.name}."
         redirect_to root_path
      else
        render :new
      end
 end

  private
  def secure_params
     params.require(:contact).permit(:name, :email, :content)
   end
end

Where do this parameters go to if there is no initialize method that sets them to instance variables and the default behavior of the 'new' method (inherited from the Ruby's Object class) does nothing with passed in parameters?

Why do they end up being set as instance variables? (something to do with the attr_accesors?)


Solution

  • You are including ActiveModel::Model which defines the initialize method that sets the values.