slu col候选人铁路4

我的rails应用程序中有Job模型和Location模型。 我使用postgresql作为数据库。所以我在我的工作模型中将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 

因此,如果您当前的Job保留location_ids = [1,2,3],那么从Location表中我们找到id = 1,2,3的位置。 然后加入他们的名字。