Richlewis
Richlewis

Reputation: 15384

Partial name Object is not a valid Ruby identifier

I am rendering a partial as part of my Ajax call and am getting an error

 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.):

I haven't seen this before and am not sure how it is being generated. In this case 94 is the returned value of @subtotal

I was also hoping someone could clarify how the partial is rendered (i.e naming convention of views) when i do

<%= j render partial: @object %>

So in my case I have a section that holds the Subtotal of items in a users shopping cart

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 %>');

The name of my partial is _subtotal.html.erb, located at /views/subtotal/_subtotal.html.erb

Can anybody see if i have done anything wrong here?

Thanks

Upvotes: 1

Views: 1433

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52357

Here

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

you are passing the @subtotal object as an argument to render partial:, but it expects a string name of the partial.

Two options:

1) move the partial to cart_items folder and

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

2) leave the partial where it is and

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

Regarding variable @subtotal:

before_action :subtotal, only: %i(show destroy)

private

def subtotal
  @subtotal ||= CartItem.subtotal
end

Thus you will have @subtotal variable DRY.

Upvotes: 1

Pavan
Pavan

Reputation: 33542

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.)

The problem is here '<%= j render partial: @subtotal %>'. @subtotal holds the value of CartItem.subtotal which is 94.0. When you are rendering a partial, you should specify the name of the partial which in your case should be subtotal. And since the location of the partial is in /views/subtotal, it should be "<%= j render partial: 'subtotal/subtotal' %>"

Upvotes: 2

Related Questions