9

我正在使用 gems Workflow、Paper Trail 和 Friend ID。

为了使用 Paper Trail 跟踪状态更改,我重写了 persist_workflow_state 以显式更新工作流列,以便 Paper Trail 可以捕获更改。

https://github.com/geekq/workflow#integration-with-activerecord

def persist_workflow_state(new_value)
  update_attribute self.class.workflow_column, new_value
end

现在,我已经引入了没有 slug 列的友好 ID,并且在达到上述方法时出现错误。

undefined method `slug=' for #<ModelName:0x007f81cf342cd8>

有什么帮助吗?

4

3 回答 3

16

现在,我介绍了没有 slug 列的 Friendly ID

我不知道你在这里的确切意思,但简单地说,这就像试图在没有钥匙的情况下启动汽车


友好ID

FriendlyID 的工作方式是使用slug(或其他标识符)列来创建 slugged URL,并根据 slugged ID 进行查找:

extend FriendlyId
friendly_id :name, use: [:slugged, :finders]

这允许 gem 根据idslug属性进行查找

如果您错过了该slug列,这将阻止它工作,从而导致您的错误。解决这个问题的方法是:

  1. 使用 slug 列
  2. 使用创建一个 slug 属性attr_accessor

如果你想尝试第二个选项,你可以试试这个:

#app/models/ModelName.rb
attr_accessor :slug
于 2014-01-28T10:01:51.073 回答
5

Richard Peck 是正确的,您必须添加slug字段。

但是很多人感到困惑,因为 FriendlyID 生成的friendly_id_slugs表包含 sluggable_id 和 sluggable_type 字段。

create_table "friendly_id_slugs", force: :cascade do |t|
t.string   "slug",                      null: false
t.integer  "sluggable_id",              null: false
t.string   "sluggable_type", limit: 50
t.string   "scope"
t.datetime "created_at"
t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
t.index ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id"
t.index ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type"
end

基本上它为历史模块生成friendly_id_slugs 表。看看他们关于History__Avoiding_404_s_When_Slugs_Change的文档:http : //norman.github.io/friendly_id/file.Guide.html#History__Avoiding_404_s_When_Slugs_Change

于 2017-03-10T14:25:55.590 回答
1

基本点是,如果您使用友好的 ID gem,那么您需要在相关的 ActiveModel 表中添加一个 slug 列。

示例:在我的项目模型中添加一个 slug

每个项目都有一个名称(属性)。

class Project < ApplicationRecord
      extend FriendlyId
      friendly_id :name, use: :slugged        

      validates :name, :state, presence: true
end

1. 运行迁移以添加 slug 列

这可以在 Rails 中轻松完成:

 rails g migration AddSlugToProjects slug

2.不要忘记索引!:

确保在 slug 列上添加索引:

class AddSlugToProjects < ActiveRecord::Migration[5.2]
  def change
    add_column :projects, :slug, :string
    add_index :projects, :slug
  end
end

现在你要去参加比赛了!

于 2018-11-05T10:10:57.190 回答