Skip to main content

How do I update value from one scaffold with the value of another scaffold?

Databases • Asked by Tatiane Stivelman

I'm doing a project that contains a stock, I first created the stock scaffold like this:

rails generate scaffold stock name:string amount:float kind:string

And then a stock_flow scaffold like this:

rails g scaffold stock_flow in_out:string time:datetime name:string amount:float kind:string origin_destiny:string stock:belongs_to

Now I want that every time that is inserted a new item at stock_flow, it searches the name inserted in the stock table and:
1) if it doesn't exists, creates a new item in stock (with the same name, amount and kind just inserted in stock_flow)
2) if it exists and the in_out field is "in" update the stock.amount to stock.amount+ the amount just inserted in stock_flow
3) if it exists and the in_out field is "out" update the stock.amount to stock.amount - the amount just inserted in stock_flow
I didn't change nothing in the code, so models, controllers and views are in the same way that when the scaffolds were generated.
I'm really lost and don't know how to do it, could somebody please help me?


Hey Tatiane,

You can do this pretty easily with an after_create callback on the StockFlow model.

Roughly, it'd probably look something like this:

class StockFlow
  after_create :update_stock

    def update_stock
      stock = Stock.find_by(name: name)

        if stock.present?
        case in_out
        when "in"
              stock.update(amount: stock.amount + amount)
          when "out"
              stock.update(amount: stock.amount - amount)
            end

        else
          Stock.create(name: name, amount: amount, kind: kind)
        end
    end
end

It worked very well, thanks


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.