我正在使用Friendly_id gem。我还嵌套了我的路线:

# config/routes.rb
map.resources :users do |user|
  user.resources :events
end

所以我有这样的网址 /users/nfm/events/birthday-2009.

在我的模型中,我希望事件标题的范围限定为用户名,以便两者 nfmmrmagoo 可以有活动 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 ?我可以覆盖这个吗?

有帮助吗?

解决方案

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

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

  • :strip_diacritics 已替换为 :strip_non_ascii.

    我决定改用 Stringex String#to_url 而是通过覆盖 normalize_friendly_id

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top