【问题标题】:Finding records by a slug instead of id in Rails在 Rails 中通过 slug 而不是 id 查找记录
【发布时间】: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


    【解决方案1】:

    after_create :create_slug 更改为before_create :create_slug

    如果要使用after_create,则必须在设置slug后保存对象。

    【讨论】:

    • 解决了,谢谢!我不认为您可以调用 before_create 并传入一个依赖于 created_at 字段的方法。
    猜你喜欢
    • 2010-10-03
    • 2022-11-11
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多