dimanche 20 décembre 2015

undefined method `name' for nil:NilClass rails with slug?

when I attempt to run my code, I got the error above. I try to transform the url products with FriendlyId gem . It works but when I try to see my product, I got this error :

NoMethodError in Products#show
undefined method `name' for nil:NilClass

Request
Parameters:
{"name"=>"tablette-chocolat-guanaja"}

Here's my models/product.rb :

has_many :order_items, dependent: :destroy
extend FriendlyId
friendly_id :name, use: :slugged
before_save :update_slug

def update_slug
    self.slug = name.parameterize
end

def to_param
    slug
end

my products_controller.rb :

before_action :set_product, only:[:show]

def show
    @order_item = current_order.order_items.new
end

private

def set_product
    @product = Product.find_by_slug(params[:id])
end

my view/show.html.erb :

<%= render "product_show", product: @product, order_item: @order_item %>

and _product_show.html.erb :

<p ><%= @product.name %></p>
<%= form_for order_item, remote: true do |f| %>
  <%= f.number_field :quantity, value: order_item.quantity.to_i, class: "form-control", min: 1, max: 99 %>
  <%= f.hidden_field :product_id, value: product.id %>
  <p><%= currency_euro product.price %></p></br>
  <p><%= image_tag product.image %></p>
  <p><%= image_tag product.image_pres1 %></p>
  # etc.

Any idea ?

Aucun commentaire:

Enregistrer un commentaire