为什么我在使用stringex时遇到错误“无法找到id = ni-hao-wo-zhen-de-henhaoma的文章”?

时间:2015-06-06 13:32:19

标签: ruby-on-rails slug

我想使用stringex来获得更友好的网址。现在我的步骤如下:

(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)文章/ _article.html.erb包括:

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

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

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

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'

1 个答案:

答案 0 :(得分:2)

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

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

要回答您的错误,会发生MATCH (n:User) RETURN n ORDER BY n.Followers DESC LIMIT 10 SET n:Influence 正在设置@article并且很可能通过ID找到记录

before_filter

由于@article = Article.find(params[:id]) 是文章slug,你想要做的是用slug来代替。因此,跳过show_filter进行show动作,并专门为show动作创建另一个before_filter。如下所示。

params[:id]

<强>更新

使用inherited_resources gem,您可能希望实现自己的show动作(以下代码未经测试,我无法保证,因为我之前从未使用过gem)

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