固定装置会触发模型回调吗? [英] Do fixtures trigger model callbacks?

查看:53
本文介绍了固定装置会触发模型回调吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在User.rb中有一个带有以下代码的User模型:

Say I have a User model with the following code in User.rb:

before_create :create_dependencies
after_create :build_inbox

我还有一个users.yml文件,其中定义了许多用户固定装置.

And I also have a users.yml file with a bunch of user fixtures defined in it.

当我运行rake db:fixtures:load时,它似乎没有触发回调.

When I run rake db:fixtures:load, it doesn't appear to trigger the callbacks.

  1. 这是预期的工作方式吗?如果是这样,为什么他们要这样设计?
  2. 加载夹具时是否有办法强制触发回调?

推荐答案

这是预期的工作方式吗?如果 那么,为什么他们要这样设计?

Is this how it is expected to work? If so, why did they design it this way?

是的,灯具不使用回调.我假设这是出于性能原因.无需实例化模型,将数据直接加载到数据库中更快.

Yes, fixtures do not use callbacks. I'm assuming this is for performance reasons. It is quicker to load the data straight into the database without instantiating the model.

是否有一种方法可以强制触发 加载时的回调数量 装置?

Is there a way to force the triggering of the callbacks when loading fixtures?

我不知道.您有几种选择.一种是构建设备,就好像回调已被触发一样.也就是说,手动创建回调将要使用的数据.例如,如果您有一个散列了用户密码的回调,则需要手动散列密码,然后将该散列存储在固定装置中.

Not that I know of. You have a couple options. One is to build your fixtures as if the callbacks were already triggered. That is, manually create the data that the callbacks would. For example, if you have a callback which hashes a user's password you would need to hash the password manually and then store that hash in the fixture.

第二种解决方案(强烈建议!)是使用工厂.工厂确实会触发回调,并允许您使用虚拟属性等.这是因为工厂每次都会实例化模型.一种流行的宝石是工厂女郎.另一个可以尝试的方法是机械师.我还针对该主题创建了铁路广播情节.

The second solution (and highly recommended!) is to use factories. Factories do trigger callbacks and allow you to use virtual attributes, etc. This is because they do instantiate the model each time. One popular gem is Factory Girl. Another one to try is Machinist. I have also created a Railscasts episode on the topic.

这篇关于固定装置会触发模型回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆