Why should you explicitly specify a scope using friendly_id?

I use the friendly_id gem. I also have nested routes:

# config/routes.rb map.resources :users do |user| user.resources :events end 

So, I have URLs like /users/nfm/events/birthday-2009 .

In my models, I want the event header to be bound to the username, so that both nfm and mrmagoo can have birthday-2009 events without punching them.

 # app/models/event.rb def Event < ActiveRecord::Base has_friendly_id :title, :use_slug => true, :scope => :user belongs_to :user ... end 

I also use has_friendly_id :username in my user model.

However, in my controller, I only pull out events related to the user who is logged in (current_user):

 def EventsController < ApplicationController def show @event = current_user.events.find(params[:id]) end ... end 

This does not work; I get an error ActiveRecord::RecordNotFound; expected scope but got none ActiveRecord::RecordNotFound; expected scope but got none .

 # This works @event = current_user.events.find(params[:id], :scope => 'nfm') # This doesn't work, even though User has_friendly_id, so current_user.to_param _should_ return "nfm" @event = current_user.events.find(params[:id], :scope => current_user) # But this does work! @event = current_user.events.find(params[:id], :scope => current_user.to_param) 

SO, why should I explicitly specify: scope if I restrict it to current_user.events? And why does current_user.to_param need to be called explicitly? Can I override this?

+4
source share
1 answer

I had the same problem with friendly_id 2.2.7, but when I upgraded to friendly_id 3.0.4 in my Rails 2.3.5 application, everything works. I tested all 4 finds you mentioned in my application and they work.

Something to keep in mind is a few API changes that may affect you. The ones I came across were:

  • :strip_diacritics been replaced by :strip_non_ascii .

    I decided to switch to Stringex String#to_url instead, overriding normalize_friendly_id

  • resource.has_better_id? now !resource.friendly_id_status.best?

  • resource.found_using_numeric_id? now resource.friendly_id_status.numeric?

+4
source

All Articles