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.