Flowdock

Notes posted by daybreaker

RSS feed
March 23, 2016
1 thank

RE: RE: FALSE: Creates record by given attributes only if table is empty

keredson is still a little off on the behavior.

>> Where in reality this would grab the “first” record (say w/ email “john@smith.com”), and change its email to “derek@somwhere.com”, a fairly surprising action that doesn’t obviously fail, leading to some pretty subtle bugs.

This isn’t right, as if you look at the source it calls: “first || create(attributes, &block)”

So in the example of:

User.first_or_create(email: 'derek@somwhere.com')

it would find the first user with any email, and return it. And thats it. The attributes passed in as params are only used in the event that first returns no matches, and create is called.

I’m using it in a way similar to:

Foo.where(bar: baz_params[:bar]).first_or_create(baz_params)

This will find the first Foo where bar is equal to the bar sent from baz_params. If none is found, it will create it. It’s useful for me when importing large amounts of data where I know there will be duplicate records.