加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么必须使用friendly_id显式指定范围?

发布时间:2020-12-17 02:26:24 所属栏目:百科 来源:网络整理
导读:我正在使用friendly_id gem.我也有嵌套的路线: # config/routes.rbmap.resources :users do |user| user.resources :eventsend 所以我有像/ users / nfm / events / birthday-2009这样的网址. 在我的模型中,我希望事件标题的范围限定为用户名,这样nfm和mrma
我正在使用friendly_id gem.我也有嵌套的路线:

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

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

在我的模型中,我希望事件标题的范围限定为用户名,这样nfm和mrmagoo都可以拥有生日 – 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;预期范围但没有.

# 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呢?为什么需要显式调用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.

我决定通过覆盖normalize_friendly_id来切换到Stringex的String#to_url> resource.has_better_id?现在是!resource.friendly_id_status.best?> resource.found_using_numeric_id?现在是resource.friendly_id_status.numeric?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读