我可以将基于属性的动态查找器的范围限定为对象吗?
别介意我,我搞砸了我的属性名称:(
这是完全可能的,使用我使用的确切语法 - 你只需要能够拼写!
我似乎无法理解这个工作,这似乎是一个足够常见的情况,必须有一个解决方案,但我没有运气使用正确的术语来获得有用的谷歌结果,
我想这样做:
u = User.first
u.clients.find_or_create_by_email('[email protected]')
效果是一个新的<。 code>Client 是用 user_id = u.id
创建的。
我可以通过 has_many
关系获得很好的动态查找器吗?如果没有,为什么
? >:)
Don't mind me, I fricked up my attribute names :(
This is entirely possible, using the exact syntax I used - you just need to be able to spell!
I can't seem to get this to work, and it seems like a common enough scenario that there must be a solution, but I'm not having any luck with the correct terminology to get a helpful Google result.
I want to do this:
u = User.first
u.clients.find_or_create_by_email('[email protected]')
With the effect that a new Client
is created with user_id = u.id
.
Can I get the nice dynamic finders through a has_many
relationship? If not, why?
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此
如果您设置了 has_many 关系,则 方法有效。但是,如果您在 Client 对象上设置了任何验证,它不会引发验证错误,并且如果验证失败,它将默默失败。
执行此操作时,您可以在控制台中检查输出,
并且将设置 user_id 但不会设置客户端的 id,因为验证失败并且未创建客户端
因此,仅当您传递客户端的所有必需属性时,才应创建客户端对象和客户端对象的验证已成功通过。
因此,假设您的客户模型除了电子邮件之外还对名称进行了验证,那么您应该这样做
This
works if you have has_many relationship set. However, it won't raise validation error if you have any validations set on your Client object and it will silently fail if the validation fails.
You can check the output in your console when you do
and the user_id will be set but not the id of client because the validation has failed and the client is not created
So this should create the client only if you pass all the required attributes of client object and the validation for client object has passed successfully.
So lets say your client model has validation on name as well apart from email then you should do
这是完全可能的,使用我使用的确切语法 - 你只需要能够拼写!
This is entirely possible, using the exact syntax I used - you just need to be able to spell!