Forum: Ruby on Rails REST with :name as unique identifier, rather than :id

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
73d4d83b7e74797ad6699c39ad5c5ffe?d=identicon&s=25 Tom Taylor (Guest)
on 2007-04-05 15:01
(Received via mailing list)
Hi all,

Is it possible to implement REST with :name as a unique identifier of
a model, instead of the :id? Having readable (literally) URLs is
important to my application as many URLs are announced at conferences
or read out over the phone.

For example, I'd like to do:

/branches
/branches/bristol
/branches/bristol;edit

Cheers,

Tom
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2007-04-05 15:36
(Received via mailing list)
On Apr 5, 2007, at 9:00 AM, Tom Taylor wrote:
> /branches/bristol
> /branches/bristol;edit
>
> Cheers,
>
> Tom

In your controller, you just need to replace:

Branch.find(params[:id])

with:

Branch.find_by_name(params[:id])

and then possibly add to your Branch model:

class Branch
   def to_param
     self.name
   end
end

so URL generation will do the right thing if you have:

edit_branch_url(@branch)
or
edit_branch_url(:id => @branch)

-Rob

Rob Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
73d4d83b7e74797ad6699c39ad5c5ffe?d=identicon&s=25 Tom Taylor (Guest)
on 2007-04-05 16:28
(Received via mailing list)
On 5 Apr, 14:36, Rob Biedenharn <R...@AgileConsultingLLC.com> wrote:
> class Branch
>    def to_param
>      self.name
>    end
> end
>
> so URL generation will do the right thing if you have:
>
> edit_branch_url(@branch)
> or
> edit_branch_url(:id => @branch)

Thanks Rob,

That's amazingly simple... Any other gotchas I should be aware of?

Cheers,

Tom
This topic is locked and can not be replied to.