【发布时间】: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