Reputation: 1425
I am following Ryan Bates railscasts video of friendly url. I am trying to implement that on my Category model by overriding the to_param
method.
Seems like it's not working, or I am missing something.
Below is my url before overriding:
localhost:3000/search?category_id=1
After overriding the to_param
the url remained same.
Following is my code:
Category model
class Category < ActiveRecord::Base
enum status: { inactive: 0, active: 1}
acts_as_nested_set
has_many :equipments, dependent: :destroy
has_many :subs_equipments, :foreign_key => "sub_category_id", :class_name => "Equipment"
has_many :wanted_equipments, dependent: :destroy
has_many :services, dependent: :destroy
validates :name, presence: true
validates_uniqueness_of :name,message: "Category with this name already exists", scope: :parent_id
scope :active, -> { where(status: 1) }
def sub_categories
Category.where(:parent_id=>self.id)
end
def to_param
"#{id} #{name}".parameterize
end
end
Controller
def search_equipments
begin
if (params.keys & ['category_id', 'sub_category', 'manufacturer', 'country', 'state', 'keyword']).present?
if params[:category_id].present?
@category = Category.active.find params[:category_id]
else
@category = Category.active.find params[:sub_category] if params[:sub_category].present?
end
@root_categories = Category.active.roots
@sub_categories = @category.children.active if params[:category_id].present?
@sub_categories ||= {}
Equipment.active.filter(params.slice(:manufacturer, :country, :state, :category_id, :sub_category, :keyword)).order("#{sort_column} #{sort_direction}, created_at desc").page(params[:page]).per(per_page_items)
else
redirect_to root_path
end
rescue Exception => e
redirect_to root_path, :notice => "Something went wrong!"
end
end
route.rb
get "/search" => 'welcome#search_equipments', as: :search_equipments
index.html.erb
The line which is generating the url
<%= search_equipments_path(:category_id => category.id ) %>
Upvotes: 0
Views: 1036
Reputation: 239290
You are generating URLs in such a way as to ignore your to_param
method. You're explicitly passing a value of only the ID to be used as the :category_id
segment of your URLs. If you want to use your to_param
-generated ID, then you need to just pass the model to the path helper:
<%= search_equipments_path(category) %>
Upvotes: 1