为什么在使用 stringex 时出现错误 "Couldn't find article with id=ni-hao-wo-zhen-de-henhaoma"?

why I got the error "Couldn't find article with id=ni-hao-wo-zhen-de-henhaoma" when using stringex?

我想使用 stringex 更友好 url。现在我的步骤如下:

(1) 在名为文章的模型中:

  acts_as_url :title, :url_attribute => :slug

  def to_param
   slug
  end

(2) 篇文章#show:

def show
  debugger
  show! do |format|
  format.html # show.html.erb
     format.json { render json: @article }
  end
end

(3) articles/_article.html.erb包括:

<%= link_to(article_url(article)) do %>
... 
<% end %>

并正确生成html标签,如:http://localhost:8000/articles/ni-hao-wo-zhen-de-henhaoma

当我点击(2)中生成的link时,出现错误:

ActiveRecord::RecordNotFound in ArticlesController#show
Couldn't find Article with id=ni-hao-wo-zhen-de-henhaoma

我在ArticlesController#show的入口下了一个断点,但是在它之前就出现了上面的错误

我还应该做什么步骤?

已更新:根据@jvnill 的提醒,我认为回溯可能有帮助:

activerecord (3.2.21) lib/active_record/relation/finder_methods.rb:344:in `find_one'
activerecord (3.2.21) lib/active_record/relation/finder_methods.rb:315:in `find_with_ids'
activerecord (3.2.21) lib/active_record/relation/finder_methods.rb:107:in `find'
activerecord (3.2.21) lib/active_record/querying.rb:5:in `find'
inherited_resources (1.4.1) lib/inherited_resources/base_helpers.rb:51:in `resource'
cancancan (1.10.1) lib/cancan/inherited_resource.rb:12:in `load_resource_instance'
cancancan (1.10.1) lib/cancan/controller_resource.rb:32:in `load_resource'
cancancan (1.10.1) lib/cancan/controller_resource.rb:25:in `load_and_authorize_resource'
cancancan (1.10.1) lib/cancan/controller_resource.rb:10:in `block in add_before_filter'

请先阅读指南,以便更好地理解流程。

http://guides.rubyonrails.org/v3.2.13/action_controller_overview.html#filters

为了回答您的错误,发生的是 @article 被设置在 before_filter 中,它很可能通过 id

找到记录
@article = Article.find(params[:id])

由于 params[:id] 是文章 slug,您要做的是通过 slug 查找。因此,跳过 show 动作的 before_filter 并创建另一个专门用于 show 动作的 before_filter。类似下面的内容。

before_filter :fetch_article, except: :show
before_filter :fetch_article_by_slug, only: :show

private

def fetch_article
  @article = Article.find(params[:id])
end

def fetch_article_by_slug
  @article = Article.find_by_slug!(params[:id])
end

更新

使用 inherited_resources gem,您可能想要实现自己的显示操作(以下代码未经测试,我无法保证,因为我从未使用过 gem之前)

actions :all, except: [:show]

def show
  @article = Article.find_by_slug!(params[:id])
end