鼻涕虫候选人 rails 4

slug candidates rails 4

我的 rails 应用程序中有 Job 模型和 Location 模型。我将 postgresql 用作 database.so 我在我的作业模型中将 location_ids 作为数组字段用于保存位置。我在我的应用程序中使用 FeriendlyId 使我的 url 友好。当我去我的工作展示页面时,我变得很友好 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

您需要定义一个自定义方法来生成您的 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。

您可以使用如下内容:

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

因此,如果您当前的职位 location_ids = [1,2,3] 然后从 Location table 我们找到 id = 1,2,3 的位置。然后加入他们的名字。