I have an xml file the user imports data from. This creates a record in the Player model.
At the same time, I want a record to be created in the Membership association.
Both of the above should only be triggered if the record does not already exist.
This is a shortened version of the method:
@player = self.players.find_or_initialize_by_name_and_archetype(name, archetype)
if @player.save
self.memberships.create(:player_id => @player.id)
end
Now find_or_initialize_by works, but a Membership is still created for each player, basically ignoring the if condition.
How can one go about doing this in a concise way?
If
@playergets set from a find, or an initialize, calling save on it can still return true, even if it’s not a new record—try it out in console by finding an object, not changing anything, calling save on it, and you’ll still get true so long as it’s a valid object.That being said, I think you want your condition to be more along the lines of