我有一個現有的方法來查詢某些模型,他們正在查詢基於category_id
和sub_category
。在着陸頁上,它用於生成像這樣的網址localhost:3000/search?category_id=208
,它用於包含基於該類別的結果。現在,我實施了friendly_id
寶石,我能夠生成如下localhost:3000/search?category_id=metal-processing-machine-tool
的網址。但看起來像這影響了現有的搜索功能,因爲雖然它顯示基於所選category_id的正確url,但它根本不顯示結果。其他詞語查詢不會發生。如何在實現friendly_id slug後更改rails應用上的現有搜索查詢?
以下是我現有的搜索功能: 搜索
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 ||= {}
@countries = Country.active.all
@manufacturers = Manufacturer.active.all
@states = State.active.where("country_id = ?", params[:country]) if params[:country].present?
@states ||= {}
@equipments = Equipment.active.filter(params.slice(:manufacturer, :country, :state, :category_id, :sub_category, :keyword))
else
redirect_to root_path
end
rescue Exception => e
redirect_to root_path, :notice => "Something went wrong!"
end
end
這是怎麼了我目前產生的URL。
<%= search_equipments_path(:category_id => category.slug) %>
這個以前就像下面這樣。而不是category.slug
它是category.id
並正確使用查詢。
<%= search_equipments_path(:category_id => category.id) %>
我迷路了,因爲我在執行friendly_id後無法獲得預期的搜索結果。有人可以告訴我該如何解決這個問題?
更新與 category.rbclass Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
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 should_generate_new_friendly_id?
true
end
end
類別表
create_table "categories", force: :cascade do |t|
t.string "name", limit: 255
t.integer "parent_id", limit: 4
t.integer "status", limit: 4, default: 1
t.integer "lft", limit: 4, null: false
t.integer "rgt", limit: 4, null: false
t.integer "depth", limit: 4, default: 0, null: false
t.integer "children_count", limit: 4, default: 0, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug", limit: 255
end
Category.new
會給
<Category id: nil, name: nil, parent_id: nil, status: 1, lft: nil, rgt: nil, depth: 0, children_count: 0, created_at: nil, updated_at: nil, slug: nil>
默認情況下,枚舉將創建範圍。因此,「active」和「inactive」已經存在。刪除你的'active'的定義。 – yzalavin