[英]Before Create in Active Record
I would like to setup a before_create for all of my modules 我想为所有模块设置一个before_create
what i have been trying is: 我一直在尝试的是:
module ActiveRecord
module UserMonitor
require 'securerandom'
before_create :attach_uuid
def attach_uuid
self.uuid = SecureRandom.uuid.gsub("-","")
end
end
end
This does not seem to be working. 这似乎不起作用。 if i go into each module and add it in there it works, but i want to do it on a global scale.
如果我进入每个模块并将其添加到那里,它可以工作,但是我想在全球范围内做。
Any thoughts or ideas on how i can achieve this in this manner? 关于如何以这种方式实现这一目标的任何想法或想法? i know i could do it in triggers and such but i don't want to go that route and i would like to avoid hitting every module/class in case i need to change something.
我知道我可以在触发器等中做到这一点,但我不想走那条路线,我想避免碰到每个模块/类,以防万一我需要改变一些东西。
Currently using Ruby 1.9.3 Can not currently upgrade my app until i make future code changes. 当前使用Ruby 1.9.3,直到我将来进行代码更改之前,当前无法升级我的应用程序。
Thanks! 谢谢!
An other solution - I use, is to put the logic for UUID in an own module, that you include. 我使用的另一种解决方案是将UUID的逻辑放在您自己包含的模块中。 I already have some (class-) methods I add to my AR, like
set_default_if
, so it was a good place for me. 我已经有一些添加到AR中的(类)方法,例如
set_default_if
,所以对我来说这是一个好地方。
module MyRecordExt
def self.included base
base.extend ClassMethods # in my case some other stuff
base.before_create :attach_uuid # now add the UUID
end
def attach_uuid
begin
self.uuid = SecureRandom.uuid
rescue
# do the "why dont we have a UUID filed?" here
end
end
# some other things not needed for add_uuid
module ClassMethods
include MySpecialBase # just an eg.
def default_for_if(...)
...
end
end
end
and then 接着
class Articel < ActiveRecord::Base
include MyRecordExt
...
end
In general I avoid doing something for ALL models modifying AR base - I made the first bad experience with adding the UUID to all, and crashed with devise GEMs models ... 总的来说,我避免对所有修改AR基础的模型做任何事情-我在向所有人添加UUID方面经历了第一次糟糕的经历,并因设计GEM模型而崩溃...
If you define attach_uuid
in the ActiveRecord module, can't you just call the before_create :attach_uuid
at the top of each controller? 如果您在ActiveRecord模块中定义
attach_uuid
,是否不能只在每个控制器的顶部调用before_create :attach_uuid
? This is DRY. 这是DRY。
Is there a UserMonitor controller that you could add it to? 您可以将其添加到UserMonitor控制器吗?
class UserMonitor < ActiveRecord::Base
before_create :attach_uuid
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.