Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails first or initialize by one value, but add more values if created

Take the following for example:

GroupMember.where(:member_id => 4).first_or_initialize

What if I wanted to say something like this-

If GroupMember with a member_id of 4 exists, "find it". Otherwise, create a GroupMember with the member_id of 4 AND a group_id of 7.

So I want the above statement to only check for the member_id - But if it doesn't exist, I want it to create a GroupMember with multiple attributes. How would I write that? I am using rails 4.0.

like image 313
Luigi Avatar asked Jan 17 '14 16:01

Luigi


Video Answer


1 Answers

This also works:

GroupMember.where(member_id: 4).first_or_initialize(group_id: 7) 

The attributes passed to first_or_initialize are only used when it creates the new record, and they're merged with the attributes from the "where" clause.

like image 71
scottb Avatar answered Sep 21 '22 15:09

scottb