In Rails 3, how can I retrieve a record by looking up on a virtual attribute? I have a name
column and a slug
that does a simple modification to it (see code below). How can I do a "reverse lookup" by slug
to name
?
I'm trying to find the right code for the find_by_slug
method below:
class Brand < ActiveRecord::Base
has_many :sale_items
validates :name, :uniqueness => true
def slug
self.name.downcase.gsub(/\s/, '-')
end
def self.find_by_slug(given_slug)
first(slug: given_slug)
end
end
When I try find_by_slug
in the Rails console I'm given an Unknown key: slug
error.
This question seems similar but I'm not sure if it's the same as my problem. I'd appreciate some insight and help!