我使用的是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?我可以重写这个吗?