Rails find_or_create_by 不止一个属性? [英] Rails find_or_create_by more than one attribute?

查看:30
本文介绍了Rails find_or_create_by 不止一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

active-record 中有一个很方便的动态属性叫做 find_or_create_by:

There is a handy dynamic attribute in active-record called find_or_create_by:

Model.find_or_create_by_(: => "")

但是如果我需要通过多个属性 find_or_create 怎么办?

But what if I need to find_or_create by more than one attribute?

假设我有一个模型来处理称为 GroupMember 的 Group 和 Member 之间的 M:M 关系.我可以有很多 member_id = 4 的实例,但我不想要不止一次 member_id = 4 和 group_id = 7 的实例.我想弄清楚是否可以做这样的事情:

Say I have a model to handle a M:M relationship between Group and Member called GroupMember. I could have many instances where member_id = 4, but I don't ever want more than once instance where member_id = 4 and group_id = 7. I'm trying to figure out if it's possible to do something like this:

GroupMember.find_or_create(:member_id => 4, :group_id => 7)

我意识到可能有更好的方法来处理这个问题,但我喜欢 find_or_create 的想法带来的便利.

I realize there may be better ways to handle this, but I like the convenience of the idea of find_or_create.

推荐答案

多个属性可以用一个连接:

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(如果不想立即保存记录,请使用 find_or_initialize_by)

(use find_or_initialize_by if you don't want to save the record right away)

上述方法在 Rails 4 中已弃用.新的方法是:

The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

编辑 2: 并非所有这些都被排除在轨道之外,只是特定于属性的那些.

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

例子

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

变成了

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

这篇关于Rails find_or_create_by 不止一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆