由多个属性的Rails find_or_create? [英] Rails find_or_create by more than one attribute?
问题描述
有一个方便的动态属性在主动记录称为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?
说我有一个模型来处理M:组和成员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.
推荐答案
多个属性可以使用连接的和
:
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)
编辑:上面的方法去precated在导轨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.
<一个href="https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md">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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!