Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Tatiane Stivelman asked in Databases

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?

Reply

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
Reply

It worked very well, thanks

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,831+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.