Search code examples
ruby-on-railsparametersroutesruby-on-rails-4vanity-url

Unable to change the parameter from id to a custom variable in Rails


I've been racking my brain trying to figure out something that should be extremely simple, so I'm sure I'm just overlooking something and a fresh set of eyes might be useful since all my code is seemingly blurring together. I'm attempting to create vanity URLS for a site that allows users to create categories and then post relevant stories based on those categories. So, for example, I would like users to access /categories/movies in order to view the movie section. If I set it up to use the category id, /categories/1, it works no problem. For whatever reason, rails keeps trying to use the id parameter to find the category as opposed to the title parameter. I'm using Ruby 2.0.0 and Rails 4.0. I've read that the "find_by" method will become deprecated soon, so if there's a better way to handle this, that'd be great. Here's the relevant code:

Categories Controller

def show
 @categories = Category.find_by_title(params[:title])
 @category = Category.find_by_title(params[:title])
 @posts = Post.where(category: set_category).all
end

Routes.rb

resources :categories

get "/categories/:title" => "categories#show"

Terminal readout when rendering page

Processing by CategoriesController#show as HTML
Parameters: {"id"=>"Movies"}

Just to reiterate, the parameters should read {"title"=>"Movies"} not id. Like I said, I'm sure it's something extremely simple that I've overlooked. Any help would be appreciated. Thanks.


Solution

  • I had to implement vanity urls as well and followed this blog post/tutorial

    You pretty much create a slug in your model with the vanity-url, so

    class Category < ActiveRecord::Base
    
      def slug
        title.downcase.gsub(" ", "-")  
      end
    
      def to_param
        "#{slug}"
      end
    
    end
    

    Your show action in your controller would use the find_by_slug method

    I think there is a gem that does this as well called friendly_id and here is a railscast but I have not personally used it

    Hope this helps