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
2
Answers
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:
So in your case, you would use something like this:
I’ve made a few assumptions:
name
attribute (seo training
)has_many
locations, each of which have aname
attributeWe 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 yourseo-training-mumbai-tokyo
slug.You can use something like the following:
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.