Is there a way to use something other than the an object’s ID in a
REST-ful API?
For example, if an application stores a collection of plants, can a
plant be referenced by the ‘scientific_name’ rather than the
‘primary_key’? If so how?
Taking it one step further, is there a way to automatically strip out
underscores from the scientific name before doing a find?
This would be an ideal URL:
/plants/Lilium_humboldtii (instead of /plants/345)
where this plant’s scientific name is ‘Lilium humboldtii’.
Is there a way to use something other than the an object’s ID in a
REST-ful API?
For example, if an application stores a collection of plants, can a
plant be referenced by the ‘scientific_name’ rather than the
‘primary_key’? If so how?
Taking it one step further, is there a way to automatically strip out
underscores from the scientific name before doing a find?
This would be an ideal URL:
/plants/Lilium_humboldtii (instead of /plants/345)
where this plant’s scientific name is ‘Lilium humboldtii’.
You can use anything in a route (subject to HTTP URL format specs). In
your model, you can override #to_param to change what gets put in the
URL by the _path helper, and in the controller you can use params[:id]
any way you’d like. To work with a user URL like so:
User:
def to_param
self.username
end
UsersController:
def show @user = User.find_by_username(params[:id])
end
That will work with the standard map.resources routes (as long as the
param doesn’t contain route separator chars (period, slash, question
mark).
Swapping spaces and underscores is easy. Just use #gsub.