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



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

(1)在文章模型中:

  acts_as_url :title, :url_attribute => :slug
  def to_param
   slug
  end

(2)文章#显示:

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

(3) the articles/_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'

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

http://guides.rubyonrails.org/v3.2.13/action_controller_overview.html过滤器

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

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

由于params[:id]是文章段塞,您要做的是通过段塞来查找。所以跳过show action的before_filter,专门为show action创建另一个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,你可能想要实现你自己的show动作(下面的代码是未经测试的,我不能保证它,因为我从来没有使用过这个gem)

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

最新更新