将额外数据传递给 find_or_create [英] Passing extra data to find_or_create
本文介绍了将额外数据传递给 find_or_create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于 rails,我一直想知道的是能够将额外数据传递给 rails 中的 find_or_create 方法.例如,我不能执行以下操作
Something I've always wondered about rails is the ability to pass extra data to find_or_create methods in rails. For example, I can't do the following
User.find_or_create_by_name('ceilingfish', :email => 'an_email@a.domain', :legs => true, :face => false)
我可以做到
u = User.find_or_create_by_name('ceilingfish')
u.update_attributes(:email => 'an_email@a.domain', :legs => true, :face => false)
但这更难看,而且还需要三个查询.我想我可以做到
But that's uglier, and also requires three queries. I suppose I could do
User.find_or_create_by_name_and_email_and_face_and_legs('ceilingfish','an_email@a.domain',true, false)
但这意味着我知道email
、legs
和face
的值是什么.有谁知道是否有一种非常优雅的方式来做到这一点?
But that kind of implies that I know what the values of email
, legs
and face
are. Does anyone know if there's a really elegant way of doing this?
推荐答案
试试这个:
User.find_or_create_by_name(:name=>'ceilingfish',
:email => 'an_email@a.domain', :legs => true, :face => false)
当您有附加参数要find_or_create_by_
时,您必须将所有参数作为散列传递.
When you have additional parameters to find_or_create_by_
, you have to pass all the parameters as a hash.
User.create_with(
email: 'an_email@a.domain',
legs: true, face:false
).find_or_create_by(:name=>'ceilingfish')
这篇关于将额外数据传递给 find_or_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文