开发者

Rails - Save another Model's object on before_save callback

开发者 https://www.devze.com 2023-02-19 05:55 出处:网络
Can I call a \"save\" to an object of model A inside the \"before_save\" callback of another model B?

Can I call a "save" to an object of model A inside the "before_save" callback of another model B?

the case: I have an Event model which has Artists. When I'm saving an Event I need to associate it with th开发者_StackOverflowose artists and, if the Artist still doesn't exist, I need to create it and save it. (Just a string is passed, not the Object, that's why he can not exist on Event-creation time)

So, the question is: can I call an artist.save on the Event's before_save?

A controversial comment was posted here: http://apidock.com/rails/ActiveRecord/Callbacks/before_save but the "observed sometimes" is really scaring.


It's hard to prove a negative, but a quick scan through the open tickets in Lighthouse doesn't show anything related to the comment you found.

In general though, you might want to push the Artist assignment/save up the chain a bit to the before_validation callback. That way, you can require the Artist in the Event model and catch any issues with Artist creation in the Event validations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号