Frage

Before everything i would like to thank you for your help

I have a model like this:

  attr_protected nil
  belongs_to :product
  belongs_to :user
  before_create :add_ammount

  def carted_product_price(ammount, price)
    ammount * price
  end

  def add_ammount
    carted_product = CartedProduct.where(:product_id => self.product_id, :user_id => self.user_id)
    if carted_product
      carted_product.first.ammount += self.ammount
      carted_product.first.update_attributes(:ammount => carted_product.first.ammount)
    else
      self.save
    end
  end

it saves buying orders in a table called Carted_Products connected to Users and Products in the belogings

the problem is that when the Before create executes i want it to update the record in the table adding the ammount passed by the controller if the record already exists and if not, create one, as far as iv done, it updates the ammount but STILL CREATES A NEW one with the passed params in the order, i want it only to update, not to do both actions when the record is found

thnx for your patience

EDIT:

Tried returning false after the update attributes, it cancels the filter, and dont create or update attributes

War es hilfreich?

Lösung

Return false in the before_create filter to prevent the object form being saved. add_amount is not responsible for saving the object, and shouldn't call save by itself.

Andere Tipps

You cannot do this in before_create filter. You need to fetch existing CartedProduct in controller where you're calling create.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top