validates_presence_of заставляет after_initialize быть названным со странным сам

Используйте sqlcmd вместо osql, если это - база данных 2005 года

5
задан pupeno 22 November 2009 в 10:37
поделиться

2 ответа

I think you're hitting a rails bug I recently battled with. See This blog entry linking to the related lighthouse bug.

My understanding is that what's happening is that some prior piece of rails code does a "select id from tablename" to see if an entry exists or matches. The object then caches that the only field that exists for the table is "id". Your code then runs, and the "attributes" value is then incorrect, reflecting only the id field.

From what I could find, this only happened when this particular code path was hit, and didn't generally upset things, except when doing validations.

What I did to get around it was wrap the after_initialise code in a begin/rescue ActiveRecord::MissingAttributeError block. Then I wrote a big note in the application and above each item indicating when a new version of rails is released, we could remove this.

Yes, I'm sure there are more elegant solutions.

def after_initialize
  begin
    # ... updates here
    # self.unique_reference = UUIDTools::UUID.random_create.to_s
  rescue ActiveRecord::MissingAttributeError
  end
end

Or you could also do:

def after_initialize
  if self.has_attribute? :measured_on
    self.measured_on ||= Date.today
  end
end
6
ответ дан 14 December 2019 в 04:40
поделиться

validates_uniqueness_of необходимо сканировать вашу базу данных на наличие записей. ActiveRecord загружает все эти другие записи как экземпляры вашей модели. Но чтобы сократить использование процессора / памяти, он не добавляет методы для атрибутов, потому что они не должны нуждаться в них для быстрой проверки существования. Однако он по-прежнему создает экземпляры всех существующих записей как экземпляров вашей модели, поэтому вызывается after_initialize.

Решение состоит в том, чтобы изменить хэш @attributes напрямую, вместо того, чтобы полагаться на аксессоры:

class Weight < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :weight, :measured_on
  validates_uniqueness_of :measured_on, :scope => :user_id
  attr_accessible :weight, :measured_on

  def after_initialize
    @attributes["measured_on"] ||= Date.today
  end
end
0
ответ дан 14 December 2019 в 04:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: