【问题标题】:Partial name Object is not a valid Ruby identifier部分名称 Object 不是有效的 Ruby 标识符
【发布时间】:2016-01-07 08:35:28
【问题描述】:

我在 Ajax 调用中呈现部分内容,但出现错误

 ActionView::Template::Error (The partial name (94.0) is not a valid Ruby identifier; make sure your partial name starts with underscore, and is followed by any combination of letters, numbers and underscores.):

我以前没有见过这个,也不确定它是如何生成的。在这种情况下,94 是 @subtotal 的返回值

我也希望有人能在我这样做时澄清部分是如何呈现的(即视图的命名约定)

<%= j render partial: @object %>

所以在我的例子中,我有一个部分保存用户购物车中商品的小计

class CartItemsController < ApplicationController
  def show
    @subtotal = CartItem.subtotal
  end

  def destroy
    @cart_item = CartItem.find(params[:id])
    @cart_item.destroy
    respond_to do |format|
      if @cart_item.destroy
        @subtotal = CartItem.subtotal
        format.js { flash.now[:success] = 'Successfully removed from cart'  }
      else
        format.js { flash.now[:error] = 'Sorry, Something went wrong' }
      end
  end
end

destroy.js.erb

$("#cart-subtotal").empty().append('<%= j render partial: @subtotal %>');

我的部分名称是_subtotal.html.erb,位于/views/subtotal/_subtotal.html.erb

谁能看看我这里有没有做错什么?

谢谢

【问题讨论】:

  • 消息说明了一切。部分文件的名称应以下划线 (_) 开头。
  • 我用我的部分名称更新了我的问题
  • 试试"&lt;%= j render partial: 'subtotal/subtotal' %&gt;"
  • 我认为这里$("#cart-subtotal").empty().append('&lt;%= j render partial: @subtotal %&gt;');你应该使用render partial: 'subtotal'
  • 这行得通(并且不得不将我的部分转移到views/cart_items/_subtotal.html.erb),我现在的问题是为什么它行得通?谢谢

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


【解决方案1】:

ActionView::Template::Error(部分名称 (94.0) 无效 红宝石标识符;确保您的部分名称以下划线开头, 后面是字母、数字和的任意组合 下划线。)

问题出在'&lt;%= j render partial: @subtotal %&gt;'@subtotal 持有 CartItem.subtotal 的值,即 94.0。当您渲染部分时,您应该指定 部分的名称,在您的情况下应该是 subtotal .而且由于partial的位置在/views/subtotal,所以应该是"&lt;%= j render partial: 'subtotal/subtotal' %&gt;"

【讨论】:

    【解决方案2】:

    这里

    ("#cart-subtotal").empty().append('<%= j render partial: @subtotal %>');
    

    您将@subtotal 对象作为参数传递给render partial:,但它需要一个部分的字符串名称。

    两种选择:

    1) 将部分移动到cart_items 文件夹和

    $("#cart-subtotal").empty().append('<%= j render partial: 'subtotal' %>');
    

    2) 将部分留在原处并

    $("#cart-subtotal").empty().append('<%= j render partial: 'subtotal/subtotal' %>');
    

    关于变量@subtotal:

    before_action :subtotal, only: %i(show destroy)
    
    private
    
    def subtotal
      @subtotal ||= CartItem.subtotal
    end
    

    因此您将拥有 @subtotal 变量 DRY。

    【讨论】:

    • 感谢@AndreyDeineko,帮助很大:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2019-04-07
    相关资源
    最近更新 更多