【问题标题】:Have friendly_id slugs only applied if condition x只有在条件 x 时才应用friendly_id slug
【发布时间】:2016-06-15 23:51:51
【问题描述】:

我已经应用了friendly_id 并且正在工作,但现在我不希望它添加一个slug,如果key_type 是4

目前我有

 extend FriendlyId
 friendly_id :value, :use => :scoped, :scope => [:category_item_key, :category_item]

并且厌倦了在模型中应用 if 语句,如下所示

  if :key_type == 4
  else
   extend FriendlyId
   friendly_id :value, :use => :scoped, :scope => [:category_item_key, :category_item]
  end

但是 if 语句似乎没有做任何事情。我想在friendly_id 中可能有一个内置的方法来完成这个(在文档中看不到任何东西)。或者也许你有其他方法来完成这件事,所以如果key_type 等于4,它就不会添加一个slug?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model rubygems friendly-id


    【解决方案1】:

    比如:

    before_create :add_slug_if_needed
    
    def add_slug_if_needed
      self.slug = 'hey_look_a_slug' unless key_type == 4
    end
    

    我建议使用此方法而不是 FriendlyId 方法,因为有条件地扩展模块似乎是一罐蠕虫!

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2017-05-05
      • 2014-08-20
      • 1970-01-01
      • 2012-07-06
      • 2016-10-28
      相关资源
      最近更新 更多