开发者

Rails - Save another Model's object on before_save callback

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜