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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With