简体   繁体   English

Rails - 在before_save回调中保存另一个Model的对象

[英]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? 我可以在另一个模型B的“before_save”回调中调用模型A的对象“保存”吗?

the case: I have an Event model which has Artists. 案例:我有一个艺术家的活动模型。 When I'm saving an Event I need to associate it with those 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) (只传递一个字符串,而不是Object,这就是他在事件创建时不能存在的原因)

So, the question is: can I call an artist.save on the Event's before_save? 所以,问题是:我可以在事件的before_save上调用artist.save吗?

A controversial comment was posted here: http://apidock.com/rails/ActiveRecord/Callbacks/before_save but the "observed sometimes" is really scaring. 一篇有争议的评论发布在这里: http//apidock.com/rails/ActiveRecord/Callbacks/before_save,但“有时观察”真的很吓人。

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. 但是,一般情况下,您可能希望将Artist赋值/将链稍微保存到before_validation回调中。 That way, you can require the Artist in the Event model and catch any issues with Artist creation in the Event validations. 这样,您可以在事件模型中要求艺术家,并在事件验证中捕获艺术家创建的任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM