ActiveRecord after_initialize与选择 [英] ActiveRecord after_initialize with select
问题描述
当我尝试调用 ActiveRecord
方法 select
的两个Rails模型时,它只会返回错误对象不支持#inspect
With two of my Rails models when I try to call the ActiveRecord
method select
it just returns the error object doesn't support #inspect
这些模型使用 after_initialize
回调,所以我怀疑这与它有关。
These models use the after_initialize
callback, so I suspect it has something to do with that.
我正在使用 after_initialize
回调像这样:
I'm using the after_initialize
callback like this:
enum state: [ :archived, :active ]
after_initialize :state_init
after_initialize :date_init
def state_init
self.state ||= :active
end
def date_init
self.report_date ||= self.event ? self.event.event_date : Date.current
end
,我需要使用 select
方法选择使用带有Postgres日期的字段按月分组的记录
and I need to use the select
method to select records grouped by month using a field that has a date with Postgres
ModelName.select("date_trunc( 'month', report_date ) as month, count(*) as count").group('month')
有什么办法可以解决此问题?
Is there any way to work around this problem?
推荐答案
基本上after_initialize方法的问题是,当您仅选择模型的列子集时,如果after_initialize方法/块访问select子句中未包含的列,则会收到MissingAttributeError。
Basically the problem with the after_initialize method is when you're only selecting a subset of columns for a model you will get a MissingAttributeError if your after_initialize method/block accesses a column that hasn't been included in the select clause.
快速解决方案之一就是将这些列包括在select子句中。但这不是正确的解决方案。您可以通过告诉过程仅在不持久保存记录时才对它进行初始化来解决它:
One of the quick solution is just include those columns in the select clause. But as this is not the right solution. You can fix it by telling the process to initialize it when the record is not persisted only as follows:
after_initialize :state_init, unless: :persisted?
after_initialize :date_init, unless: :persisted?
def state_init
self.state ||= :active
end
def date_init
self.report_date ||= self.event ? self.event.event_date : Date.current
end
这篇关于ActiveRecord after_initialize与选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!