【发布时间】:2010-12-20 03:29:21
【问题描述】:
我正在使用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)
SO,如果我将 :scope 限制为 current_user.events,为什么还需要明确指定?为什么 current_user.to_param 需要显式调用?我可以覆盖它吗?
【问题讨论】:
标签: ruby-on-rails rubygems scope nested friendly-id