0

i have to following method

before_save :save_each_item_details

def save_each_item_details
  items = itemname.length
  i = 0

  while i < items
    items = itemname.length
    if !ItemsCensu.exists?(itname: itemname[i], year: "#{date.to_s.split('-').first}")
      ItemsCensu.create(itname: itemname[i], monadaM: mm[i], quntity: quantity[i], price: price[i], tax: tax[i], year: "#{date.to_s.split('-').first}", num_invoice << invoice_num)
      i += 1
    else
      puts "test"
      i += 1
    end
  end
end

num_invoice is the array from database. invoice_num is a number like 1239

Each time I save it, I want it to to add the invoice_num into num_invoice[] without removing the old value.

For example

1st save:

invoice_num = 1234
num_invoice << invoice_num
# => 1234

2nd save:

invoice_num = 12345
num_invoice << invoice_num
# => [1234, 12345]

Is there a way to build this into my ItemsCensu.create, something like ItemsCensu.create(num_invoice: << invoice_num)?

7
  • where does invoice_num coming from? Is num_invoice database field of current object that you're saving? Commented May 25, 2020 at 21:02
  • invoice_num coming from the form before the save, you can say that its like generae a random number, any hard code solution is acceptable Commented May 25, 2020 at 21:20
  • 1
    create expects a hash of name-value. E.g. Exapmple.create(num_invoice: num_invoice << invouce_num) I'm slightly confused about your data structure, but maybe you want ItemsCensu.create(itname: itemname[i], <whatever else you have here except last>, num_invoice: [invoice_num]. Since you create a new object the value of the array will be your new element inside new array. Commented May 25, 2020 at 22:31
  • 1
    Which database are you using? if postgresql then go through the [array functions] (postgresql.org/docs/current/…) or [this example] (stackoverflow.com/a/9680411/12297707) Commented May 26, 2020 at 4:42
  • 1
    Does items_censu.update_attributes(num_invoice: items_censu.num_invoice + invoice num) solve your problem? Simply append the value to it's current array before saving Commented May 26, 2020 at 15:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.