Why callbacks for the after_find and after_initial

2019-04-29 18:20发布

The only way to define callbacks for the after_find and after_initialize events is to define them as methods. If you try declaring them as handlers using the second technique, they’ll be silently ignored.

Can anybody explain why is it so?

Why specifically for these two callbacks?

EDIT

From the book:-- Rails has to use reflec- tion to determine whether there are callbacks to be invoked. When doing real database operations, the cost of doing this is normally not significant com- pared to the database overhead. However, a single database select statement could return hundreds of rows, and both callbacks would have to be invoked for each. This slows the query down significantly. The Rails team decided that performance trumps consistency in this case. What the hell...!!!! Thats all.. Just this as explanation...!!!

1条回答
看我几分像从前
2楼-- · 2019-04-29 18:40

From the API:

The after_find and after_initialize exceptions

Because after_find and after_initialize are called for each object found and instantiated by a finder, such as Base.find(:all), we‘ve had to implement a simple performance constraint (50% more speed on a simple test case). Unlike all the other callbacks, after_find and after_initialize will only be run if an explicit implementation is defined (def after_find). In that case, all of the callback types will be called.

查看更多
登录 后发表回答