views:

160

answers:

5

I have a basic CRUD with "Company" model. To make the company name show up, I did

def to_param
  name.parameterize
end

Then I accessed http://localhost:3000/companies/american-express which runs show action in the companies controller.

Obviously this doesn't work because the show method is as following:

def show
  @company = Company.find_by_id(params[:id])
end

The params[:id] is american-express. This string is not stored anywhere.

Do I need to store the short string (i.e., "american-express") in the database when I save the record? Or is there any way to retrieve the company data without saving the string in the database?

+3  A: 

Send the ID with the parameterized value;

def to_param
    new_record? ? super : "#{id}-#{name}"
end

And when you collect the data in the show method, you can use the whole parameter;

def show
    @company = Company.find("12-american-express"); // equals to find(12)
end

There's also a plugin called permalink_fu, which you can read more about here.

Björn
Interesting solution. Leaving the "id" at the beginning of the param is interesting. I just ran `"12-american-express".to_i` and it returned `12`.
TK
Sweet and simple! Thanks @Björn.
Shripad K
A: 

I do something similar with the Category model in my blog software. If you can guarantee that the only conversion the parameterize method is doing to your company names is replacing space characters with dashes then you can simply do the inverse:

def show
  @company = Company.find_by_name(params[:id].gsub(/-/, ' '))
end
John Topley
Unfortunately, "parameterize" is much more complicated. It does does more than changing the space and case.
TK
I'm aware of that. I didn't know what constraints you have on your company names.
John Topley
A: 

Hi TK

Try permalink_fu plugin, which creates SEO friendly URLs in rails

http://github.com/technoweenie/permalink_fu

cheers

sameera

sameera207
+1  A: 

I think friendly_id is more usable.

Filip
+ 1 for friendly_id
mark
A: 

I would suggest the friendly_id gem also. It gives you the flexibility to use persited permalink slugs, also strip diacritics, convert to full ASCII etc. Basically it makes your life a lot easier, and you get "true" permalinks (no to_param and the id workaround needed) with little effort.

Oh and did i mention that the permalinks are also versioned, so you can make old outdated permalinks to redirect to the current one? :)

Tanel Suurhans