使用 Rails 4 对friendly_id 进行故障排除:在 rails 控制台中按预期工作,从控制器获取 RecordNotFound 错误 [英] Troubleshooting friendly_id w/ Rails 4: working as expected in rails console, getting RecordNotFound error from controller

查看:40
本文介绍了使用 Rails 4 对friendly_id 进行故障排除:在 rails 控制台中按预期工作,从控制器获取 RecordNotFound 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的 Rails 4 应用程序中成功地使用了friendly_id 和多个模型.我之前有两个我决定组合的模型(终端和位置).Terminals show action 之前使用friendly_id,我可以在那里访问/terminals/albany 并获取带有slug 'albany' 的终端.

I've been successfully using friendly_id with multiple models in my Rails 4 app. I previously had two models that I've decided to combine (Terminals and Locations). The Terminals show action was previously working with friendly_id, where I could visit /terminals/albany and get the Terminal with the slug 'albany'.

我已经完成了大部分重构以压缩到仅位置,并且是最后一部分(修复视图).一路上,我一直在 Rails 控制台中测试东西并使用 rspec,事情似乎按预期工作.还有其他模型仍然可以按预期工作.

I've gone through the bulk of the refactor to condense down to just Locations, and am on the last piece (fixing views). Along the way I've been testing things in Rails Console and using rspec, and things seem to work as expected. There are other models that still work as expected as well.

现在我正在处理位置的新显示页面,尝试访问/locations/albany 时出现以下错误:

Now that I'm working on the new show page for Locations, I'm getting the following error when attempting to visit /locations/albany:

ActiveRecord::RecordNotFound in LocationsController#show
Couldn't find Location with id=albany

但是,当我访问/locations/5 时,它成功加载了记录.它也适用于 Rails 控制台:

However, when I visit /locations/5, it successfully loads the record. It also works in Rails Console:

Location.find(5)                 # returns the correct location object
Location.find(5).slug            # returns 'albany'
Location.friendly.find('albany') # returns the correct location object

当我在 Rails dbconsole 中查看生成的 slug 时,它们看起来都正确生成并且没有重复.

When I look at the generated slugs in Rails dbconsole, they all look like they were generated correctly and there are no duplicates.

这是我的模型:

Class Location < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: [:slugged, :history]

  def slug_candidates
    [
      :name,
      [:name, :zip],
      [:name, :zip, :location_type],
    ]
  end
end

这是我在控制器中的显示操作:

And here's my show action in my controller:

def show
  @locations = Location.friendly.find(params[:id])
end

我被难住了!有什么提示吗?

I'm stumped! Any hints?

推荐答案

您是否尝试添加 :finders?

have you tried adding :finders?

friendly_id :slug_candidates, use: [:slugged, :history, :finders]

这篇关于使用 Rails 4 对friendly_id 进行故障排除:在 rails 控制台中按预期工作,从控制器获取 RecordNotFound 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆