REST with :name as unique identifier, rather than :id


#1

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


#2

On Apr 5, 2007, at 9:00 AM, Tom T. 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 B. http://agileconsultingllc.com
removed_email_address@domain.invalid


#3

On 5 Apr, 14:36, Rob B. removed_email_address@domain.invalid 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