我已经创建了这个模块:
应用程序/模型/问题/sluggable.rb
module Sluggable
extend ActiveSupport::Concern
included do
before_create :set_slug
end
def set_slug
if self.slug.nil?
puts 'adding slug'
self.slug = SecureRandom.urlsafe_base64(5)
end
end
end
我将其包含在模型中,如下所示:
app / models / plan.rb
class Plan < ApplicationRecord
extend FriendlyId
friendly_id :id, :use => :slugged
include Sluggable
end
但before_create不会触发。slug列是一个not_null列,因此出现数据库错误。
错误:列“ slug”中的空值违反了非空约束
如果将set_slug代码直接放入模型中,它将起作用。那么,我对Rails 5中的关注点遗漏了什么?
我想知道它是否与使用FriendlyId有关(这就是为什么我首先添加弹头的原因!)
这帮助我解决了这个问题。Friendly_Id如果为nil,则在before_validation回调中设置该段。
因此,我的模块需要在此之前“跳转”。因此,制作不与Friendly_id冲突的模块的解决方案如下。
注意,我需要更改我的钩子的方法名称(因为set_slug是Friendly_Id使用的方法)并且我必须使用prepend:true。这一起导致我的代码在Friendly_Id触发检查尝试并设置之前设置了子弹。
module Sluggable
extend ActiveSupport::Concern
included do
before_validation :set_a_slug, prepend: true
end
def set_a_slug
if self.slug.nil?
self.slug = SecureRandom.urlsafe_base64(5)
end
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句