简体   繁体   中英

ActiveRecord after_initialize with select

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM