Rails find_or_create_by more than one attribute?

后端 未结 5 835
广开言路
广开言路 2020-11-27 09:27

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

Model.find_or_create_by_(: => \"\")

5条回答
  •  隐瞒了意图╮
    2020-11-27 10:09

    Multiple attributes can be connected with an and:

    GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
    

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

    Edit: 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
    

    and

    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

    Example

    GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
    

    became

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

提交回复
热议问题