Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an ActiveRecord object without overriding initialize

I quickly ran into problems when trying to create an ActiveRecord instance that overrode initialize like this:

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

I found this post which cleared up why it is happening.

Is there anyway that I can avoid creation code like this:

e = Email.new
e.email = "[email protected]"

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

Is this possible?

like image 228
dagda1 Avatar asked Jun 29 '26 08:06

dagda1


2 Answers

e = Email.new(:email => "[email protected]")
like image 117
Trip Avatar answered Jul 01 '26 23:07

Trip


ActiveRecord::Base#new also takes a handy block variation

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

The suggestions of using the hash version in prior answers is how i typically do it if I don't want to put any logic on the actual assignment.

like image 28
jwarchol Avatar answered Jul 01 '26 23:07

jwarchol