【问题标题】:Why do you have to explicitly specify scope with friendly_id?为什么必须使用friendly_id 明确指定范围?
【发布时间】: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 这样的网址。

在我的模型中,我希望将事件标题限定为用户名,以便 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)

SO,如果我将 :scope 限制为 current_user.events,为什么还需要明确指定?为什么 current_user.to_param 需要显式调用?我可以覆盖它吗?

【问题讨论】:

    标签: ruby-on-rails rubygems scope nested friendly-id


    【解决方案1】:

    我在使用 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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 2015-11-12
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多