Search code examples
ruby-on-railsrubyruby-on-rails-3mongoidmongoid3

Find_by_slug with Mongoid method undefined


I am using Mongoid(3.0.23) and I want to add nicer URL's, I have followed this rails cast but for some reason my site throws an undefined error for the find_by_slug method. I have read about some gems I could use but it seems pointless for such a simple task.

Model

validates :slug, :uniqueness => true

before_validation :generate_url

def generate_url
  self.slug ||= self.title.parameterize if slug.blank?
end 

def to_param
  slug
end

field :slug

View

<% @events.each do |e|  %>
  <%= link_to e.title, event_path(e) %>  
<% end %>

Controller

def show
   @event = Event.find_by_slug!(params[:id])
end

Solution

  • Maybe try:

    Event.find_by(slug: params[:id])
    

    Also, not sure if it's necessary but you could specify the type:

     field :slug, type: String