ruby-on-railsrails-admin

Saving Calculated Data when using rails_admin gem


In my project i have product model and stock_in model, using rails_admin gem how can i update a quantity of a product automatically when new stock_in is created for that product?


Solution

  • Without seeing any code, it's hard to give you anything more than general advice.

    You don't need to do this through rails_admin because Rails already has hooks.

    Assuming your Product and StockIn models are related:

    class Product
      has_many :stock_ins
    end
    
    class StockIn
      belongs_to :product
    end
    

    You can just use an after_create hook on StockIn:

    class StockIn
      belongs_to :product
    
      after_create :update_product_quantity
    
      ...
    
      private
    
      def update_product_quantity
        product.update(quantity: self.quantity)
      end
    end