views:

32

answers:

2

Hi Everyone,

Say if I have a model called 'deliver' and I am using the default URL route of:

 # Install the default routes as the lowest priority.
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

So the deliver URL would be:

http://localhost:3000/deliver/123

What I am trying to work out, is how to use another field from the database alongside or instead of the ID.

For example. If I have a field in the create view called 'deliveraddress', how do I put that into the routes?

So I can have something link this:

http://localhost:3000/deliver/deliveraddress

Thanks,

Danny

+2  A: 

Since it sounds from your comments like you're trying to obfuscate the ID in your URL, I would suggest that you look at this question, which was asked a few days ago.

http://stackoverflow.com/questions/2814844/obfuscating-ids-in-rails-app

jdl
+1  A: 

First of all, the url "http://localhost:3000/deliver/123" matches either default routing rule. However, only after you declared an "resource" it will generate such a RESTful URL.

In your case, just implement the "to_param" method of Deliver model:

class Deliver < ActiveRecord::Base
  def to_param
    return self.deliveraddress
  end
end

it will generate the url you want by calling url_for method, like link_to @deliver

Do not forget to make sure you have unique deliver addresses in your database so you will never find duplicated records with one address.

After that, you need to update the finder methods in actions:

def show
  @deliver = Deliver.find_by_deliver_address!(params[:id])
end

Hope this answer will be useful.

Hozaka
Perhaps a better way would be to have to_param return "#{id}/#{deliveraddress}" then update your routes and finders to work with that, this would allow duplicates in the deliveraddress column
Daniel Beardsley