【问题标题】:slug candidates rails 4蛞蝓候选人rails 4
【发布时间】:2015-04-21 05:56:09
【问题描述】:

我的 rails 应用程序中有 Job 模型和 Location 模型。我使用 postgresql 作为数据库。所以我将 location_ids 作为我的 Job 模型中的一个数组字段来保存位置。我在我的应用程序中使用 FeriendlyId 来使我的 url 友好。当我进入我的工作展示页面时,我得到了这个友好的网址

http://localhost:3000/jobs/seo-trainee

但现在我还想在我的 url 中包含工作的位置,就像这样

http://localhost:3000/jobs/seo-trainee-mumbai-tokyo

我知道我们可以为此目的使用 slug_candidates。但我不知道我怎样才能做到这一点

目前我的工作模型中有这个

 extend FriendlyId
 friendly_id :slug_candidates, use: [:slugged, :finders]

 def slug_candidates
  [
    :title,
    [:title, :id]
  ]
 end

【问题讨论】:

    标签: ruby-on-rails friendly-id


    【解决方案1】:

    您需要定义一个自定义方法来生成您的 slug 定义,然后告诉 FriendlyId 使用该方法。

    文档给出了这个例子:

    class Person < ActiveRecord::Base
      friendly_id :name_and_location
      def name_and_location
        "#{name} from #{location}"
      end
    end
    
    bob = Person.create! :name => "Bob Smith", :location => "New York City"
    bob.friendly_id #=> "bob-smith-from-new-york-city"
    

    所以在你的情况下,你会使用这样的东西:

    class SomeClass
      friendly_id :job_name_and_location
    
      def job_name_and_location
        "#{name} #{locations.map(&:name).join(' ')}"
      end
    end
    

    我做了一些假设:

    • 您的工作模型具有 name 属性 (seo training)
    • 您的工作模型has_many 位置,每个位置都有一个name 属性

    然后我们创建一个方法来定义非友好字符串,FriendlyId 将使用该字符串来创建 slug。在这种情况下,它会提出类似SEO Training Mumbai Tokyo 的内容并使用它来创建您的seo-training-mumbai-tokyo slug。

    【讨论】:

      【解决方案2】:

      你可以使用类似下面的东西:

      extend FriendlyId
       friendly_id :slug_candidates, use: [:slugged, :finders]
      
       def slug_candidates
         locs = Location.where("id IN(?)", self.location_ids).collect{|l| l.name}.join("-") // here, we find the locations for the current job, then joins the each locations name with a '-' sign
         return self.title+"-"+locs // here, returns the job title with the location names
       end
      

      所以,如果您当前的 Job 持有 location_ids = [1,2,3] 然后从位置表中我们找到 id = 1,2,3 的位置。然后加入他们的名字。

      【讨论】:

      • 你不应该真的在 Rails 中定义 SQL,除非你在 ActiveRecord 的能力范围之外做一些疯狂的事情。使用标准关联有什么问题?
      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 2016-06-02
      • 2021-04-04
      • 2014-04-02
      • 2016-07-22
      • 2011-02-09
      • 2013-05-27
      • 1970-01-01
      相关资源
      最近更新 更多