0

I have a model that looks like:

class Product < ActiveRecord::Base

  before_create :generate_token

  def to_param
    token
  end

  private

  def generate_token

    self.token = loop do
       random_token = SecureRandom.urlsafe_base64(10, false)
       break random_token unless Product.exists?(token: random_token)
    end
  end

end

My controller looks like:

def set_product
  @product = Product.find_by(token: params[:token])
end

When I create a new product, I get the error:

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

and my show in my controller looks like:

def show
   @title = @product.name
end

my create looks like:

def create
@product = Product.new(product_params)
#@product.user_id = current_user.id
respond_to do |format|
  if @product.save
    format.html { redirect_to @product, notice: 'Product was successfully created.' }
    format.json { render action: 'show', status: :created, location: @product }
  else
    format.html { render action: 'new' }
    format.json { render json: @product.errors, status: :unprocessable_entity }
  end
end
end

Also, in my controller I have a callback that looks like:

before_action :set_product, only: [:show, :edit, :update, :destroy]

But in the rails console insert, it shows the name being inserted. the name column is being set.

the_
  • 1,183
  • 2
  • 30
  • 61

1 Answers1

2

Can you show me your url that goes to that page

if you are passing the token by product_path(token)

then try

def set_product
  @product = Product.find_by(token: params[:id]) # id instead of token
end

if it is a form then

def set_product
  @product = Product.find_by(token: params[:product][:token])
end

I am prettry sure your current params[:token] is not right that is why you cannot find the product.

sonnyhe2002
  • 2,091
  • 3
  • 19
  • 31