我正在尝试为一个简单的迷你博客应用程序创建语义 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
被覆盖。
我错过了什么?
谢谢。
最佳答案
将 after_create :create_slug
更改为 before_create :create_slug
。
如果你想使用after_create,你必须在设置slug后保存对象。
关于ruby-on-rails - Rails 中通过 slug 而不是 id 查找记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997980/