Reputation: 594
In my posts controller, right now I'm finding posts by user_id and post_id and it works perfectly fine
def find_post
@track = Track.find_by(user_id: params[:id], post_id: params[:post_id])
end
I am looking for a way to find the post instead of the user_id, by the username for example if it's finding the post like this:
/:user_id/:post_id
To something like:
/:username/:post_id
So how can I access the username parameter in the url? or is there a better process for this?
Upvotes: 0
Views: 3052
Reputation: 12514
Rails's Router maps the :placeholder
s to params
object-keys. Like
/:user_id/:slug
maps user_id
to params[:user_id]
/:username/:slug
maps username
to params[:username]
. So you can access the supplied username via params
object. and make DB calls like
user = User.find_by_username(params[:username])
@post = user.posts.find(params[:post_id])
You cannot find post directly from username
because you have no information that which username does this post belongs to. You only have user_id
as foreign_key
but not username
.
Upvotes: 1