Search code examples
arraysrubydestroy

Rails update remove number from an array attribute?


Is there a way to remove a number from an attibute array in an update? For example, if I want to update all of an alchy's booze stashes if he runs out of a particular type of booze:

Alchy has_many :stashes

Stash.available_booze_types = [] (filled with booze.ids)

Booze is also a class

@booze.id = 7

if @booze.is_all_gone
  @alchy.stashes.update(available_booze_types: "remove @booze.id")
end

update: @booze.id may or may not be present in the available_booze_types array

... so if @booze.id was in any of the Alchy.stash instances (in the available_booze_types attribute array), it would be removed.


Solution

  • I think you can do what you want in the following way:

    if @booze.is_all_gone
      @alchy.stashes.each do |stash|
        stash.available_booze_types.delete(@booze.id)
      end
    end
    

    However, it looks to me like there are better ways to do what you are trying to do. Rails gives you something like that array by using relations. Also, the data in the array will be lost if you reset the app (if as I understand available_booze_types is an attribute which is not stored in a database). If your application is correctly set up (an stash has many boozes), an scope like the following in Stash class seems to me like the correct approach:

    scope :available_boozes, -> { joins(:boozes).where("number > ?", 0) }
    

    You can use it in the following way:

    @alchy.stashes.available_boozes
    

    which would only return the ones that are available.