slu col候选人铁路4

时间:2015-04-21 05:56:10

标签: ruby-on-rails friendly-id

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

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

但是现在我还想在我的网址中包含作业所在的位置,例如

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

您可以使用以下内容:

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] 然后从位置表中我们找到id = 1,2,3的位置。然后加入他们的名字。