Search code examples
ruby-on-rails-3routesparameterized

Rails 3 - routing and parameterized name


I use this rule in my model:

  def to_param
    "#{self.name.parameterize}"
  end

and in my helper:

  def articles_menu
    menu = '<ul>'
    Article.all.each do |article|
      menu += '<li>'
        menu += link_to "#{article.name}", article
      menu += '</li>'
    end
    menu += '</ul>'
    return menu.html_safe
  end

but when I'll go to the /articles/my-new-flat, I'll get the error

ActiveRecord::RecordNotFound in ArticlesController#show

Couldn't find Article with id=my-new-flat

Missing I something else yet or is any problem in my app? I though for parameterizing of the name is needed only set up in the model the rule...


Solution

  • Use FriendlyId gem it has all what you need, here is the link https://github.com/norman/friendly_id/blob/master/README.md

    Problem with your code is that rails under the hub is trying to query your model by "id" attribute, it is not querying "name" attribute. FriendlyId gem patches this for models you want