the_
the_

Reputation: 1173

Rails Find By Token Issue

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 routes looks like:

get "products/:token" => "products#show"

and my controller looks like:

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

But I get the error: Unknown key: token, even though the token is definitely getting created (it shows in the url)

Upvotes: 0

Views: 1106

Answers (1)

BroiSatse
BroiSatse

Reputation: 44725

Use:

  @product = Product.find_by(token: params["token"])

find method always expects id.

Upvotes: 4

Related Questions