问题描述:

When using MongoMapper's find_or_create_by_attr method, is it possible to check whether the returned result was found in database or newly created?

网友答案:

You could try MyModel.find_or_initialize_by_attr then check my_obj.persisted? and call save if necessary.

网友答案:

After reviewing the MongoMapper source code, I don't really see a way to detect that. I think that method is used when you do not care whether it's an existing item or a new one. If you do care, you probably want to separate it into a find_by_attr call, check if it exists, and then call create! if it doesn't.

相关阅读:
Top