So, I’m trying to implement a bulk import, i.e. a text area, where people can write lists of their cards in the form “amount cardname”. Then Rails takes each line, finds the amount and the card name (that part is working) and adds it to the database (this part is not working).
My database:
- cards (id, name) – already filled, I do not want to create anything here
- users (id, name)
- haves (id, card_id, user_id, amount)
Relations
- user has_many haves
- card has_many haves
- have belongs_to card and user
> cards_bulk.each_line do |line| > card_data = /(^\d.?\s)(.+)/.match(line) > end
This code iterates through the text area content and regexes the right parts, so that I have my amount in card_data[0] and my card’s name in card_data[2].
Now I want to add that card to this user’s haves. If it already exists, I want to add the amount to the amount it already has. If it does not exist, I want to create it and set it’s amount to the given amount. I’m not quite sure on how I would do that.
Thanks
You can use new_record? helper to the rescue