我使用的是friendly_id寶石。我也有我的路線嵌套:爲什麼你必須使用friendly_id明確指定範圍?
# config/routes.rb
map.resources :users do |user|
user.resources :events
end
所以我有像/users/nfm/events/birthday-2009
URL。
在我的模型,我希望事件標題先限定的用戶名,這樣既nfm
和mrmagoo
可以有事件birthday-2009
沒有他們被猛擊。
# app/models/event.rb
def Event < ActiveRecord::Base
has_friendly_id :title, :use_slug => true, :scope => :user
belongs_to :user
...
end
我在我的用戶模型中也使用了has_friendly_id :username
。
然而,在我的控制,我只拉出相關的事件,是誰在(CURRENT_USER)登錄的用戶:
def EventsController < ApplicationController
def show
@event = current_user.events.find(params[:id])
end
...
end
這不工作;我收到錯誤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,爲什麼我需要明確指定:範圍,如果我把它限制current_user.events呢?爲什麼需要明確調用current_user.to_param?我可以重寫這個嗎?