mercredi 16 novembre 2016

Rails select has_many though get the right Id

I'm trying to pass the size of a product to a order with select. the product has many sizes with has_many though. but when pass show the wrong size, someone know why?

Size Model

 attr_accessible :size
  has_many :orders 
  has_many :sizeship
  has_many :products, :through => :sizeship

Product Model

 has_many :orders
  has_many :sizeships
  has_many :sizes, through: :sizeships

Order Model

  belongs_to :cart
  belongs_to :product, touch: true
  belongs_to :size

Cart Model

  belongs_to :user
  has_many :orders

Product Controller

def show
   @product = Product.cached_find(params[:id])

  @sizes_for_dropdown = @product.sizes.collect { |s| [s.size, s.id] }

end

Cart Controller

 def add
    product = Product.find(params[:id])

    if product
     if product.buyable?(current_user)
        current_user.cart = Cart.new #if current_user.cart.nil?
        size =  product.sizes.find_by_id(params[:size_id])
        quantity = params[:quantity].to_i > 0 ? params[:quantity].to_i : 1
       order = current_user.cart.orders.find_by_product_id_and_status_and_size_id(product.id, nil, product.sizes.nil? ? nil : product.sizes.find { |l| l.id } )

        if order.nil? # create new order
          order = Order.new
          order.product = product
          order.size = product.sizes.find { |k| k.id } 

          current_user.cart.orders << order
        else # increase quantity
          order.quantity += quantity
          order.save
        end

        redirect_to product_path(product)
        flash[:success] = "Success"
      else
        redirect_to product_path(product)
        flash[:error] = " Error"

      end
    else
      redirect_to :shop, flash[:error] = 'Error'
    end
  end

Aucun commentaire:

Enregistrer un commentaire