问题
I have Job model and Location model in my rails application. I am using postgresql as a database.so i have location_ids as an array field in my Job model for holding locations. I am using FeriendlyId in my application to make my url friendly. when i go to my job show page i am getting this friendly url
http://localhost:3000/jobs/seo-trainee
but now i also want to include the locations the job has in my url , something like this
http://localhost:3000/jobs/seo-trainee-mumbai-tokyo
i know we can use slug_candidates for this purpose. but i dont know how can i achieve this exactly
currently i have this in my Job model
extend FriendlyId
friendly_id :slug_candidates, use: [:slugged, :finders]
def slug_candidates
[
:title,
[:title, :id]
]
end
回答1:
You need to define a custom method to generate your slug definition, and then tell FriendlyId to use that method.
The documentation gives this example:
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"
So in your case, you would use something like this:
class SomeClass
friendly_id :job_name_and_location
def job_name_and_location
"#{name} #{locations.map(&:name).join(' ')}"
end
end
I've made a few assumptions:
- Your job model has a
name
attribute (seo training
) - Your job model
has_many
locations, each of which have aname
attribute
We then create a method which defines the non-friendly string which FriendlyId will use to create a slug from. In this case it'll come up with something like SEO Training Mumbai Tokyo
and use that to create your seo-training-mumbai-tokyo
slug.
回答2:
You can use something like the following:
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
So, if your current Job holds location_ids = [1,2,3] then from Location table we find the locations with id = 1,2,3. Then join their names.
来源:https://stackoverflow.com/questions/29764036/slug-candidates-rails-4