我正在使用friendly_id gem。我也嵌套了我的路线:
# config/routes.rb
map.resources :users do |user|
user.resources :events
end
所以我有像/users/nfm/events/birthday-2009
.
在我的模型中,我希望将事件标题限定为用户名,以便两者都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)
所以,如果我将它限制为current_user.events,为什么我需要明确指定 :scope ?为什么 current_user.to_param 需要显式调用?我可以覆盖这个吗?