开发者

Initializing an ActiveRecord object without overriding initialize

开发者 https://www.devze.com 2023-01-22 09:35 出处:网络
I quickly ran into problems when trying to create an ActiveRecord instance that overrode initialize like this:

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

class Email < ActiveRecord::Base
  belongs_t开发者_开发百科o :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 = "info@info.com"

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

Is this possible?


e = Email.new(:email => "info@info.com")


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消