Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: decrement attribute in table when other record is created
    primarykey
    data
    text
    <p>So I have two models: <strong>Product</strong> and <strong>Sale</strong>. they are related via a <strong>has_many :trough</strong> association and both have the same attributes and attribute names (sale has one more tough):</p> <p><strong>THE CODE SNIPPETS:</strong></p> <pre><code># Product Model class Product &lt; ActiveRecord::Base attr_accessible :qty, :color, :name, :price, :size, :type, :code has_many :orders has_many :sales, :through =&gt; :orders end # Sale Model class Sale &lt; ActiveRecord::Base attr_accessible :qty, :color, :name, :salesman_name, :price, :size, :type, :code has_many :orders has_many :productos, :through =&gt; :orders end </code></pre> <p>What I want to do is to <strong>decrement</strong> the <em>Products>Quantity</em> attribute of a specific record (product) every time a new Sale is created with it's name on it... The substraction must be equal to the value of "qty" set in the new sale creation in relation with the created product...</p> <p>The app is a very simple inventory system where I track <strong>stock items</strong> and sales, let's give a pratical example: Imagine I have a product called "Socks" in the <strong>Products</strong> Database and I have "30" as the <strong>qty</strong> attribute of that product, Then someone sells <strong>two socks</strong> (creates a new sale with 2 socks in the app): in that case I want the value of "Socks" to be updated to 28 in the Products database automatically.</p> <p>I've been reading and I think this may can be accomplished with an after_create callback in the sale model with an ActiveRecord transaction, but I'm not sure how to implement this, Can someone help me? By the way, I was thinking about using something similar to this thing here:</p> <pre><code>after_create :decrement_stock def decrement_stock Sale.transaction do Product.transaction do @substraction = product.sale(params[:qty]) product.update_attributes!(:qty =&gt; @qty - @substraction) end end end </code></pre> <p>But I'm pretty sure it isn't going to work, Please Point me in the right directions... I've been struggling with this one a little. </p> <p>Thanks and have a nice day.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload