Rails find_or_create by more than one attribute?

Posted by tybro0103 on Stack Overflow See other posts from Stack Overflow or by tybro0103
Published on 2010-06-15T15:27:00Z Indexed on 2010/06/15 15:32 UTC
Read the original article Hit count: 249

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?

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)

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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord