调用metod和/或动作控制器时出错

时间:2015-05-17 06:57:52

标签: ruby-on-rails ruby-on-rails-4 routes action

我有这个问题: 我应该减少line_item的属性“数量”。 所以我创建了一个button_to来做到这一点。 问题是即使我在line_item的控制器中创建了“less”的新动作并将其添加到路径中,我的功能也不起作用。 你能告诉我这是什么问题吗?

的routes.rb

resources :line_items do
    post :less, on: :collection     
end

Line_item控制器 在这个文件中我包含了set_cart方法(它可以工作)所以我有可能使用@cart vaiable 我写了before_action:set_cart,只写:[:create,:less]

def less
    puts "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"
    #Rails sa di dover prendere l' ID da product per eseguire il find :D
product = Product.find(params[:product_id])
    #aggiungiamo un prodotto in piu'
    #ritorna un current_item
    @line_item = @cart.less_items(product.id)
respond_to do |format|
  if @line_item.save
    format.html { redirect_to store_url}
            #a respond_to passiamo il blocco con la @current_item
            #si passa un blocco perchè è definito cosi il metodo
            format.js   { @current_item = @line_item} 
    format.json { render :show, status: :created, location: @line_item }
  else
    format.html { render :new }
    format.json { render json: @line_item.errors, status: :unprocessable_entity }
  end
end

购物车型号:

def less_items(product_id)  
    current_item = line_items.find_by(product_id: product_id)
    if current_item && current_item > 1
        current_item.quantity -= 1
    else
        current_item = line_items.build(product_id: product_id)
    end
    current_item
end

控制台对我说:

Console

新问题:

向TomášDundáček致谢我明白我必须编辑cancan能力文件以允许更少的方法通过。现在我还有问题。图为:

enter image description here

2 个答案:

答案 0 :(得分:1)

作为新问题的答案:

这一行:

if current_item && current_item > 1

需要更改为

if current_item && current_item.quantity > 1

答案 1 :(得分:0)

不要想,但我有这些:

include CurrentCart
before_action :set_cart, only: [:create,:less]    
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
#cancan
load_and_authorize_resource