Initializing an ActiveRecord Object without Overriding Initialization

I quickly ran into problems when trying to create an ActiveRecord instance that reconfigured initialization as follows:

class Email < ActiveRecord::Base
  belongs_to :lead
  def initialize(email = nil)
    self.email = email unless email.nil?
  end
end

I found this post that found out why this is happening.

In any case, I can avoid creating the creation code as follows:

e = Email.new
e.email = "info@info.com"

I would like to create and initialize my objects in one line of code.

Is it possible?

+3
source share
2 answers
e = Email.new(:email => "info@info.com")
+3
source

ActiveRecord :: Base # new also accepts convenient block variation

email = Email.new do |e|
  e.email = params[:email] unless params[:email].blank?
end

Suggestions for using the hash version in previous answers is how I usually do it if I don't want to put any logic on the actual destination.

+1
source

Source: https://habr.com/ru/post/1772189/


All Articles