Update a record in a table and from this create a record in another table

0

I have a table called products, and when I select a product, it must be deducted from that product from the product table and a record must be created in another table called cart

The schema tables are: ActiveRecord :: Schema.define (version: 20170623134129) do

create_table "carritos", force: :cascade do |t|
    t.integer  "producto_id"
    t.float    "precio"
  end

  create_table "productos", force: :cascade do |t|
    t.integer  "cantidad_existencia"
    t.text     "nombre"
    t.text     "descripcion"
    t.float    "precio"
  end

the models are:

class Producto < ActiveRecord::Base
    has_many :carrito
end

class carrito  < ActiveRecord::Base
    belongs_to :producto
end

the driver is:

def ajustar
  @producto.cantidad_existencia -= 1 # se resta de la cantidad de productos
  @producto.update(ajustar_producto)
end

in the product model I think this logic should go, but it does not do anything.

class Producto < ActiveRecord::Base
  has_many :carrito

  after_save :subir_al_carrito

  private
    def subir_al_carrito
      Carrito.producto_id = self.id # id de la tabla producto
      Carrito.precio      = self.precio # precio de la tabla producto
      Carrito.save
    end
end
    
asked by rrg1459 24.06.2017 в 19:12
source

1 answer

0

That's right, the logic should go in the model, but you need to adjust the code of the subir_al_carrito method to create the record:

def subir_al_carrito
  Carrito.create!(producto_id: id, precio: precio)
end

The method will create a new record in Carrito with id and precio of the product. As you can see, it is not necessary to use self to read the values of the attributes (it is only necessary when you assign them).

    
answered by 24.06.2017 / 19:36
source