开发者

Human readable URL causes a problem in Ruby on Rails

开发者 https://www.devze.com 2023-01-03 18:22 出处:网络
I have a basic CRUD with \"Company\" model. To make the company name show up, I did def to_param name.parameterize

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 america开发者_如何学运维n-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?


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.


I think friendly_id is more usable.


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


Try permalink_fu plugin, which creates SEO friendly URLs in rails

http://github.com/technoweenie/permalink_fu

cheers

sameera


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? :)

0

精彩评论

暂无评论...
验证码 换一张
取 消