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

This is the reference I use - http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize

The method's source states:

def first_or_initialize(attributes = nil, &block)
  first || new(attributes, &block)
end

So, if the record is not found - it initialises a new one and passes to a block.

You can use it:

GroupMember.where(:member_id => 4).first_or_initialize do |member|
  member.group_id = 7
end

It will execute block for new record only.


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.