first_or_create

The behaviour of first_or_create can be a bit of a gotcha.

In the method below, I use a couple of attributes to find a ShopCollection. Then I pass in a hash of further attributes (first_or_create also takes a block if you prefer).




s = ShopCollection.where(:client_id => client_id,
:handle => work.subject_shop_handle_parent(parent_id)).first_or_create(
:body_html => "Main Category",
:title => work.subject_shop_handle_parent(parent_id),
:shop_products => [],
:image => subjectcode_array)

The hash only gets called if the first_or_create resulted in a create. If it finds an existing record, the hash, or alternatively the block, won't be executed. And the hash attributes aren't persisted on a save of s.

So to update an existing record, you need to do something like the above, then also a save or update_column, such as:

s.image = subjectcode_array
s.save