Forum: Ruby on Rails using unique varchar instead of 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.
Dorian M. (Guest)
on 2006-01-18 19:21
(Received via mailing list)
Hi,
I just signed up so 'hello everybody'.

As the title suggests, I was wondering if there was an easy way to
specify that I want all actions/controls to be based upon a particular
parameter rather than :id (in this case :unique_name). I don't :id to
appear in URLs or elsewhere, I want it all to work from :unique_name.

It seems like something that I should be able to do globally for a
project, but I'm not sure where to start.

thanks

dorian

--
I do things for love or money
--
+44 (0)7941 219 501
--
aim:oulalipo | yahoo:tachekent
Wilson B. (Guest)
on 2006-01-18 21:46
(Received via mailing list)
On 1/18/06, Dorian M. <removed_email_address@domain.invalid> wrote:
> Hi,
> I just signed up so 'hello everybody'.
>
> As the title suggests, I was wondering if there was an easy way to specify that I want 
all actions/controls to be based upon a particular parameter rather than :id (in this case 
:unique_name). I don't :id to appear in URLs or elsewhere, I want it all to work from 
:unique_name.
>
> It seems like something that I should be able to do globally for a project, but I'm not 
sure where to start.
>

I just did this for a project I'm working on.  In your routes.rb file,
define routes that make sense based on the way you want your URLs to
look.  This means using something other than :id, probably.

In your model that has :unique_name as its unique identifier, make
sure you've got validates_uniqueness_of :unique_name, and then add:
def to_param
  self[:unique_name]
end

to_param is the method that is called when you do something like:
link_to :action => 'blah', :unique_name => @some_model_instance
By default it just returns the id attribute, but you can override that.

Then go through your code and replace any:
@blah = Model.find(params[:id])
with
@blah = Model.find_by_unique_name(params[:unique_name])

..and you should be done.
This topic is locked and can not be replied to.