我可以动态范围基于属性的发现者为一个对象?
-
19-09-2019 - |
题
我不介意,我fricked了我的属性名称:(
这是完全可能的,使用我用确切的语法 - !你只需要能够拼出
我似乎无法得到这个工作,而且它似乎是一个足够常见的场景,必须有一个解决方案,但我并没有用正确的术语来得到一个有用的谷歌造成的任何运气。
我想这样做:
u = User.first
u.clients.find_or_create_by_email('example@example.com')
使用一个新的Client
与user_id = u.id
产生的效果。
我能否通过has_many
关系得到了很好的动态发现者?如果不是,为什么?
由于:)
解决方案 2
这是完全可能的,使用我用确切的语法 - !你只需要能够拼出
其他提示
此
u = User.first
u.clients.find_or_create_by_email('example@example.com')
如果你的has_many关系组工作。但是,如果你有你的客户对象上设置任何验证它不会提高验证错误,如果验证失败,它会悄悄地失败。
您可以检查输出在控制台当你
u.clients.find_or_create_by_email('example@example.com') # => #<Client id: nil, email: 'example@example.com', name: nil, user_id: 1, another_attribute: nil, active: true, created_at: nil, updated_at: nil>
和USER_ID将被设置,但客户端的不是ID,因为验证失败,并且所述客户端不创建
所以这应该创建客户端只有在你通过客户端对象的所有必需的属性和客户对象的验证已成功通过。
因此,可以说你的客户端模型对姓名验证以及除了电子邮件,那么你应该做的。
u.clients.find_or_create_by_email_and_name('example@example.com', 'my_name') #=> #<Client id: 1, email: 'example@example.com', name: 'my_name', user_id: 1, another_attribute: nil, active: true, created_at: "2009-12-14 11:08:23", updated_at: "2009-12-14 11:08:23">
不隶属于 StackOverflow