【问题标题】:Conditionally reset slug using friendly_id gem使用 friendly_id gem 有条件地重置 slug
【发布时间】:2018-03-22 14:56:22
【问题描述】:

我的应用使用 friendly_id gem 以通常的方式分配 slug:

class Organization < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged
  strip_attributes
end

当用户更改组织名称时,默认情况下 slug 不会更改。但我想让用户选择重置 slug 以匹配名称。

从控制台来看,这很简单:

>> organization.update(slug: nil)

Friendly_id 使用 before_validate 钩子跳转并生成一个新的 slug。但是如果我尝试使用 OrganizationsController#update 方法将slug 设置为nil,它就不起作用了:

Started PATCH "/organizations/slo-mo-100?organization%5Bslug%5D=" for 127.0.0.1 at 2017-10-10 16:37:30 -0600
Processing by OrganizationsController#update as HTML
  Parameters: {"organization"=>{"slug"=>""}, "id"=>"slo-mo-100"}
  Organization Load (0.5ms)  SELECT  "organizations".* FROM "organizations" WHERE "organizations"."slug" = $1 ORDER BY "organizations"."id" ASC LIMIT $2  [["slug", "slo-mo-100"], ["LIMIT", 1]]
   (0.3ms)  BEGIN
  SQL (4.1ms)  UPDATE "organizations" SET "slug" = $1, "updated_at" = $2 WHERE "organizations"."id" = $3  [["slug", nil], ["updated_at", "2017-10-10 22:37:30.077956"], ["id", 1]]
   (0.2ms)  ROLLBACK
Completed 500 Internal Server Error in 24ms (ActiveRecord: 6.2ms)

PG::NotNullViolation - ERROR:  null value in column "slug" violates not-null constraint

我希望 #update 操作就像控制台一样,即在传入值设置为 nil 时分配一个新的 slug。

【问题讨论】:

    标签: ruby ruby-on-rails-5 friendly-id


    【解决方案1】:

    事实证明,解决方案非常简单。问题是更新参数通过将 slug 设置为空字符串 ({"slug"=&gt;""}) 而不是 nil。我正在使用strip_attributes gem 将空字符串转换为nil,但是直到friendly_id 已经检查slug 字段是否为nil 之后才调用strip_attributes

    我通过将回调的顺序切换为在friendly_id 之前触发strip_attributes 解决了这个问题:

    class Organization < ApplicationRecord
      extend FriendlyId
      strip_attributes
      friendly_id :name, use: :slugged
    end
    

    【讨论】:

      猜你喜欢
      • 2015-12-27
      • 2015-07-30
      • 1970-01-01
      • 2014-03-19
      • 2014-11-20
      • 1970-01-01
      • 2015-08-08
      • 2018-07-15
      • 2014-10-22
      相关资源
      最近更新 更多