4

我正在使用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 需要显式调用?我可以覆盖这个吗?

4

1 回答 1

4

我对friendly_id 2.2.7 有完全相同的问题,但是当我在我的Rails 2.3.5 应用程序中更新到friendly_id 3.0.4 时,一切正常。我已经测试了您在我的应用程序中提到的所有 4 个查找调用,它们都有效。

需要注意的是一些可能会影响您的 API 更改。我遇到的是:

  • :strip_diacritics已替换为:strip_non_ascii

    String#to_url我决定通过覆盖改用 Stringexnormalize_friendly_id

  • resource.has_better_id?就是现在!resource.friendly_id_status.best?

  • resource.found_using_numeric_id?就是现在resource.friendly_id_status.numeric?

于 2010-05-09T13:04:40.640 回答