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