rails to_param无效

时间:2017-03-22 12:36:17

标签: ruby-on-rails ruby

我正在关注友情网址的Ryan Bates railscasts视频。我试图通过覆盖to_param方法在我的类别模型上实现它。 好像它没有用,或者我错过了什么。 以下是覆盖之前的我的网址:

localhost:3000/search?category_id=1 

覆盖to_param之后,网址保持不变。

以下是我的代码:

类别模型

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

控制器

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

生成网址的行

<%= search_equipments_path(:category_id => category.id ) %>

1 个答案:

答案 0 :(得分:1)

您正在以忽略to_param方法的方式生成网址。您明确传递的值仅限ID ,以用作您网址的:category_id段。如果您想使用to_param生成的ID,那么您只需将模型传递给路径助手:

<%= search_equipments_path(category) %>