find_or_create_by in Rails 3 and updating for creating records

前端 未结 3 760
执念已碎
执念已碎 2020-12-05 01:17

I\'m not sure if I should be updating records this way or if I\'m missing something.

I have a table with 5 columns (not including timestamps and id) 3 of which are d

3条回答
  •  甜味超标
    2020-12-05 02:00

    Actually, there is a way without any hacking. Instead of find_or_create_by you can use find_or_initialize_by and set updated atributes with tap

    Available.find_or_initialize_by_room_id_and_bookdate_and_source(
      room.id, 
      (params[:date].to_date)+index, 
      data.class.to_s#
    ).tap do |a|
      a.price = night.price
      a.spots = night.spots
    end.save!
    

    Initially this can seems cluttered, but it is doing exactly what you asked for. Find the record, instanciate it if not found and update atributes. this could be called "find_and_update_or_create_by", fortunatelly nobody did that. ;) Hope this help.

提交回复
热议问题