ActiveRecord after_initialize with select

被刻印的时光 ゝ 提交于 2019-12-22 00:25:31

问题


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

These models use the after_initialize callback, so I suspect it has something to do with that.

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

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?


回答1:


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.

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



回答2:


I am facing the similar issue with you.

In the end, I have decided to remove the after_initialize method and set default value instead in db (migration).

Hope this helps.



来源:https://stackoverflow.com/questions/34867700/activerecord-after-initialize-with-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!