Rails find_or_create by more than one attribute?
- by tybro0103
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.