【问题标题】:friendly_id gem using associated model fields使用关联模型字段的friendly_id gem
【发布时间】:2013-04-11 09:30:21
【问题描述】:

如果我们必须在更新关联记录时为模型生成 slug,我们应该怎么做。例如,我正在使用模型 User 和 UserProfile,并且 slug 是 user.user_profile.name。创建新用户时,也会保存关联的 user_profile。为新的用户记录生成 slug。但是当更新 user_profile 并更改名称时,slug 不会更新。请帮忙。

【问题讨论】:

    标签: ruby-on-rails friendly-id


    【解决方案1】:

    在最新版本的friendly_id 中,您可以定义一个方法来指定何时重新生成slug(尽管这可能不是您需要的):

      def should_generate_new_friendly_id?
        name_changed? || super
      end
    

    您可以在 UserProfile 类上使用保存后回调将 slug 设置为 nil 并强制 friendly_id 重新生成 slug:

    if name_changed?
      user.slug = nil
      user.save
    end
    

    这应该根据文档处理它:http://norman.github.io/friendly_id/

    【讨论】:

      【解决方案2】:

      您可以覆盖should_generate_new_friendly_id? 方法。这样您就可以控制何时生成新的 slug。

      你可以这样做

      class User < ActiveRecord::Base
        extend FriendlyId
        friendly_id :my_friendly_id_method, :use => :slugged
      
        def should_generate_new_friendly_id?
          user_profile.changed?
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-09
        • 2013-01-17
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        • 2014-08-10
        相关资源
        最近更新 更多