【问题标题】:error calling metod and/or action controller调用方法和/或动作控制器时出错
【发布时间】:2015-05-17 06:57:51
【问题描述】:

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

Routes.rb

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

Line_item 控制器 在这个文件中,我包含了 set_cart 方法(它有效),所以我可以使用@cart vaiable 我写了 before_action :set_cart, only: [: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

控制台对我说:

新问题:

感谢 Tomáš Dundáček,我知道我必须编辑 cancan 能力文件以允许更少的方法通过。现在我仍然有问题。图片如下:

【问题讨论】:

  • 你好像是从某个before_action重定向过来的,这可能吗?

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


【解决方案1】:

所以作为新问题的答案:

这一行:

if current_item && current_item > 1

需要改成

if current_item && current_item.quantity > 1

【讨论】:

  • 我在您回答之前先对其进行编辑:p 现在,如果我为页面充值,我会看到修改。但是我的 Ajax 不起作用.. arrgg 也许我必须为 less 创建一个新的 js 文件...
  • 是的,我创建了新文件less.js,它可以工作。Thx Tomáš Dundáček。爱你!
【解决方案2】:

别想,但我有这些:

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

【讨论】:

  • 是的,很可能是 cancan 将您重定向...另外,请尝试使用 cmets 回答,或在编辑您的原始问题时而不是回答
  • 您能做的最好的事情是尝试将puts 放入您的ApplicationController 中的rescue_from CanCan::AccessDenied 以查看是否是它
  • 我把能力放在康康舞中,以减少动作。现在我看到了puts,我也看到它进入了汽车的方法。我会给你看图片,但我还是有问题。 [2]:i.stack.imgur.com/KvAQB.png
  • 好的,所以请用新问题更新原始问题:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 2017-11-17
相关资源
最近更新 更多