Rails选择has_many但获得正确的ID

时间:2016-11-16 22:29:53

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

enter image description here enter image description here我正在尝试将产品的大小传递给带有select的订单。尽管如此,该产品有许多尺寸和has_many。 orger页面上的size.id与我在产品页面上选择的size.id不匹配。 有人知道为什么吗?

  

例如,如果在订单页面上选择产品尺寸。(2),请显示size.id(4)

尺寸模型

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

产品型号

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

订单型号

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

购物车型号

  belongs_to :user
  has_many :orders

产品控制器

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

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

end

购物车控制器

 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

日志

Started POST "/carts/add/yy" for 127.0.0.1 at 2016-11-17 00:11:16 -0200
Processing by CartsController#add as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Hf7eLJPojw+u/HCGuQtAVzADC7v0jpkw5mJ0sCmx0u4=", "score"=>"", "quantity"=>"1",  "size_id"=>"1", "commit"=>"add to basket", "id"=>"yy"}
Redirected to http://localhost:3000/products/yy
Completed 302 Found in 3471.4ms 

0 个答案:

没有答案