DataMapper first_or_create 总是设置某些字段?
我使用以下数据映射器从我的数据库创建/获取新用户:
user = User.first_or_create({:id => data['id']})
这会获取 id = data['id'] 的用户,或者如果它尚不存在则创建它。
我想知道如何设置返回对象的其他属性/字段,无论它是新记录还是现有记录?
执行此操作的唯一方法是调用 user.update({:field => value ...})
还是有更好的方法来实现此目的?
I'm using the following with datamapper to create/get a new user from my db:
user = User.first_or_create({:id => data['id']})
This gets the user with id = data['id'] or creates it if it doesn't already exist.
I want to know how to set other attributes/fields of the returned object regardless of whether it is a new record or existing?
Is the only way to do this to then call user.update({:field => value ...})
or is there a better way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您可以将其写为一行:
如果您愿意的话(或者如果您需要指定多个参数),可以使用参数的哈希值;但是,值得注意的是,只有当
first_or_create
指定的模型有效时,这才有效。例如,如果:name
是必填字段,那么这将不起作用:因为第一部分中的创建将失败。
您可以通过指定新记录所需的参数来解决此问题,例如
,但这非常痛苦,并且难以阅读。
另请注意,如果不存在这样的记录,则将
first_or_create
与:id
一起使用将尝试使用该特定:id
创建模型。这可能不是您想要的。或者,您可以使用
first_or_new
。但是,您无法对使用此方法创建的对象调用update
,因为记录不存在(尽管我相信这可能在以前版本的 DataMapper 中有效)。Well, you could write it as one line:
with hashes for the parameters if you wish (or if you need to specify more than one); however, it's worth noting that this will only work if the model as specified by the
first_or_create
is valid. If:name
were a required field, for instance, then this wouldn't work:as the creation in the first part would fail.
You could get around this by specifying the parameters needed for a new record with something like
but this is unusually painful, and is difficult to read.
Also note that using
first_or_create
with an:id
will attempt to create a model with that specific:id
, if such a record doesn't exist. This might not be what you want.Alternatively, you can use
first_or_new
. You can't callupdate
on an object created using this, however, as the record won't exist (although I believe this might have worked in previous versions of DataMapper).对于遇到这个答案的任何人来说, User.first_or_create({:id => data['id']}) 不会“获取具有 id = data['id'] 的用户,或者创建它(如果还没有)存在。”它实际上获取表中的第一条记录并将其id更改为t0 data['id']。
要实际获取具有该 id 的第一条记录,或者如果它不存在则创建它,您需要使用 where 子句:
Just for anyone coming across this answer, User.first_or_create({:id => data['id']}) does NOT "get the user with id = data['id'] or creates it if it doesn't already exist." It actually gets the first record in the table and changes its id t0 data['id'].
To actually get the first record with that id, or create it if it doesn't exist, you need to use a where clause: