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

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

问题描述

活动记录中有一个方便的动态属性,称为find_or_create_by:

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

Model.find_or_create_by_<attribute>(:<attribute> => "")

但是如果我需要通过多个属性进行查找或创建怎么办?

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

说我有一个模型来处理Group和Member之间的M:M关系,称为GroupMember.我可能有很多实例,其中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.

推荐答案

多个属性可以与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

并非所有这些因素都只是特定于属性的因素.

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天全站免登陆