【发布时间】:2014-11-17 19:55:06
【问题描述】:
我正在尝试为一个简单的迷你博客应用程序创建语义 URL,但我坚持使用 to_param 并检索记录。这是Post 模型:
class Post < ActiveRecord::Base
after_create :create_slug
validates :title, :body, :presence => true
validates :title, length: { maximum: 250 }
validates :body, length: { maximum: 5000 }
def to_param
slug
end
private
def create_slug
self.slug = slugify
end
def slugify
[year_month_day, title.parameterize].join("-")
end
def year_month_day
[created_at.year, created_at.strftime("%m"), created_at.strftime("%d")].join
end
end
现在,每次我使用link_to @post.title, @post 链接到帖子时,我都会收到此错误:
No route matches {:action=>"show", :controller=>"posts", :id=>nil} missing required keys: [:id]
show 操作如下所示:
def show
@post = Post.find_by_slug(params[:id])
end
当我执行上述操作时,它会尝试查找以 slug 作为 id 的帖子,但 slug 不是 id,所以我收到错误消息。当我使用标准的find(params[:id]) 时,它找不到记录,因为to_param 被覆盖了。
我错过了什么?
谢谢。
【问题讨论】:
标签: ruby-on-rails url activerecord model-view-controller routing