Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

ruby on rails - Do fixtures trigger model callbacks?

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

before_create :create_dependencies
after_create :build_inbox

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

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

  1. Is this how it is expected to work? If so, why did they design it this way?
  2. Is there a way to force the triggering of the callbacks when loading fixtures?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...